目錄
- 相關概念
- 生產者&消費者模型
相關概念
-
鎖:解決執行緒間沖突的問題
-
wait¬ify:解決執行緒間協作的問題
-
wait和sleep的區別
wait期間物件鎖是釋放的,而sleep只能延時,并未釋放鎖
-
呼叫wait方法:暫停正在執行的執行緒,放棄CPU執行權,并釋放資源鎖
-
呼叫notify方法:喚醒暫停的執行緒使之運行
生產者&消費者模型
場景邏輯:定義兩個類,分別為商店和顧客,顧客隨機點可樂,雞翅等食物,商店生產對應的食物,然后顧客食用食物
核心:定義一個全域物件實作多執行緒情況下執行緒間的可見,以實作執行緒協作
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("===============");
}
}
}
}
}
訂購:可樂
生產:可樂
食用: 可樂
===============
訂購:雞腿
生產:雞腿
食用: 雞腿
===============
訂購:雞翅
生產:雞翅
食用: 雞翅
參考:Java 多執行緒編程之:notify 和 wait 用法
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/95068.html
標籤:Java
下一篇:執行緒安全&Java記憶體模型
