Java並發編程中的臨盆者與花費者模子簡述。本站提示廣大學習愛好者:(Java並發編程中的臨盆者與花費者模子簡述)文章只能為提供參考,不一定能成為您想要的結果。以下是Java並發編程中的臨盆者與花費者模子簡述正文
概述
關於多線程法式來講,臨盆者和花費者模子長短常經典的模子。加倍精確的說,應當叫“臨盆者-花費者-倉庫模子”。分開了倉庫,臨盆者、花費者就缺乏了共用的存儲空間,也就不存在並不是協作的成績了。
示例
界說一個場景。一個倉庫只許可寄存10件商品,臨盆者每次可以向個中放入一個商品,花費者可以每次從個中掏出一個商品。同時,須要留意以下4點:
1. 統一時光內只能有一個臨盆者臨盆,臨盆辦法須要加鎖synchronized。
2. 統一時光內只能有一個花費者花費,花費辦法須要加鎖synchronized。
3. 倉庫為空時,花費者不克不及持續花費。花費者花費前須要輪回斷定以後倉庫狀況能否為空,空的話則花費線程須要wait,釋放鎖許可其他同步辦法履行。
4. 倉庫為滿時,臨盆者不克不及持續臨盆,臨盆者臨盆錢須要輪回斷定以後倉庫狀況能否為滿,滿的話則臨盆線程須要wait,釋放鎖許可其他同步辦法履行。
示例代碼以下:
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("臨盆了: " + 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();
}
}
}