鎖:解決線程間衝突的問題編程
wait¬ify:解決線程間協做的問題segmentfault
wait和sleep的區別多線程
wait期間對象鎖是釋放的,而sleep只能延時,並未釋放鎖dom
調用wait方法:暫停正在執行的線程,放棄CPU執行權,並釋放資源鎖ide
調用notify方法:喚醒暫停的線程使之運行線程
場景邏輯:定義兩個類,分別爲商店和顧客。顧客隨機點可樂,雞翅等食物,商店生產對應的食物,而後顧客食用食物code
核心:定義一個全局對象實現多線程狀況下線程間的可見,以實現線程協做對象
package com.noneplus; public class Main { private final Object flag = new Object(); private static String[] food = {"可樂", "雞翅", "雞腿", "披薩"}; private static String foodType; public static void main(String[] args) { Main main = new Main(); Thread store = main.new Store(); Thread customer1 = main.new Customer(); store.start(); customer1.start(); } class Store extends Thread { @Override public void run() { while (true) { synchronized (flag) { flag.notify(); if (Main.foodType==null) { System.out.println("暫無訂單"); } else { System.out.println("生產:" + Main.foodType); try { flag.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } class Customer extends Thread { @Override public void run() { while (true) { synchronized (flag) { flag.notify(); Main.foodType = Main.food[(int) (Math.random() * 3)]; System.out.println("訂購:" + Main.foodType); try { flag.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("食用: " + Main.foodType); System.out.println("==============="); } } } } }
訂購:可樂 生產:可樂 食用: 可樂 =============== 訂購:雞腿 生產:雞腿 食用: 雞腿 =============== 訂購:雞翅 生產:雞翅 食用: 雞翅