概述
對于多線程程序來說,生產者和消費者模型是非常經典的模型。更加準確的說,應該叫“生產者-消費者-倉庫模型”。離開了倉庫,生產者、消費者就缺少了共用的存儲空間,也就不存在并非協作的問題了。
示例
定義一個場景。一個倉庫只允許存放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(); } } }
新聞熱點
疑難解答