Java并發(fā)編程中的生產(chǎn)者與消費者模型簡述
概述
對于多線程程序來說,生產(chǎn)者和消費者模型是非常經(jīng)典的模型。更加準確的說,應該叫“生產(chǎn)者-消費者-倉庫模型”。離開了倉庫,生產(chǎn)者、消費者就缺少了共用的存儲空間,也就不存在并非協(xié)作的問題了。
示例
定義一個場景。一個倉庫只允許存放10件商品,生產(chǎn)者每次可以向其中放入一個商品,消費者可以每次從其中取出一個商品。同時,需要注意以下4點:
1. 同一時間內只能有一個生產(chǎn)者生產(chǎn),生產(chǎn)方法需要加鎖synchronized。
2. 同一時間內只能有一個消費者消費,消費方法需要加鎖synchronized。
3. 倉庫為空時,消費者不能繼續(xù)消費。消費者消費前需要循環(huán)判斷當前倉庫狀態(tài)是否為空,空的話則消費線程需要wait,釋放鎖允許其他同步方法執(zhí)行。
4. 倉庫為滿時,生產(chǎn)者不能繼續(xù)生產(chǎn),生產(chǎn)者生產(chǎn)錢需要循環(huán)判斷當前倉庫狀態(tài)是否為滿,滿的話則生產(chǎn)線程需要wait,釋放鎖允許其他同步方法執(zhí)行。
示例代碼如下:
public class Concurrence {
public static void main(String[] args) {
WareHouse wareHouse = new WareHouse();
Producer producer = new Producer(wareHouse);
Consumer consumer = new Consumer(wareHouse);
new Thread(producer).start();
new Thread(consumer).start();
}
}
class WareHouse {
private static final int STORE_SIZE = 10;
private String[] storeProducts = new String[STORE_SIZE];
private int index = 0;
public void pushProduct(String product) {
synchronized (this) {
while (index == STORE_SIZE) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storeProducts[index++] = product;
this.notify();
System.out.println("生產(chǎn)了: " + product + " , 目前倉庫里共: " + index
+ " 個貨物");
}
}
public synchronized String getProduct() {
synchronized (this) {
while (index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String product = storeProducts[index - 1];
index--;
System.out.println("消費了: " + product + ", 目前倉庫里共: " + index
+ " 個貨物");
this.notify();
return product;
}
}
}
class Producer implements Runnable {
WareHouse wareHouse;
public Producer(WareHouse wh) {
this.wareHouse = wh;
}
@Override
public void run() {
for (int i = 0; i < 40; i++) {
String product = "product" + i;
this.wareHouse.pushProduct(product);
}
}
}
class Consumer implements Runnable {
WareHouse wareHouse;
public Consumer(WareHouse wh) {
this.wareHouse = wh;
}
@Override
public void run() {
for (int i = 0; i < 40; i++) {
this.wareHouse.getProduct();
}
}
}
相關文章
Java C++題解leetcode 1684統(tǒng)計一致字符串的數(shù)目示例
這篇文章主要為大家介紹了Java C++題解leetcode 1684統(tǒng)計一致字符串的數(shù)目示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01
Java整合mybatis實現(xiàn)過濾數(shù)據(jù)
這篇文章主要介紹了Java整合mybatis實現(xiàn)過濾數(shù)據(jù),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2023-01-01
Java生成二維碼的兩種實現(xiàn)方式(基于Spring?Boot)
這篇文章主要給大家介紹了關于Java生成二維碼的兩種實現(xiàn)方式,文中的代碼基于Spring?Boot,本文基于JAVA環(huán)境,以SpringBoot框架為基礎開發(fā),文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-07-07
Java 枚舉類和自定義枚舉類和enum聲明及實現(xiàn)接口的操作
這篇文章主要介紹了Java 枚舉類和自定義枚舉類和enum聲明及實現(xiàn)接口的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02

