生產者消費者模式案例


該例子利用多線程實現生產者消費者模型。

兩個線程:

  • 生產者;
  • 消費者。

實現的功能:

  • 生產者生產滿,通知消費者去消費;
  • 倉庫沒有產品,通知生產者去生產。

為了使代碼可讀性強,清晰易懂,樓主建了四個Java類:

1.EventStorage:倉儲模型,用於定義生產和消費的方法;

2.Producer:生產者;

3.Consumer:消費者;

4.TestThread:用於測試。

 1 /**
 2  * 倉儲模型
 3  */
 4 public class EventStorage {
 5     
 6     //用於打印時間
 7     private List<Date> storage;
 8     
 9     //最大生產數量
10     private int maxSize;
11     
12     public EventStorage() {
13         
14         maxSize = 10;
15         storage = new LinkedList<Date>();
16     }
17     
18     //模擬生產動作
19     public synchronized void set() {
20         while (storage.size() == maxSize) {
21             try {
22                 wait();//如果生產滿,通知生產者等待
23             } catch (InterruptedException e) {
24                 e.printStackTrace();
25             }
26         }
27         
28         storage.add(new Date());
29         System.out.println("生產: "+ storage.size());
30         notifyAll();//喚醒在等待操作資源的線程(隊列)
31     }
32     
33     //模擬消費動作
34     public synchronized void get() {
35         while (storage.size() == 0) {
36             try {
37                 wait();//如果為空,通知消費者等待
38             } catch (InterruptedException e) {
39                 e.printStackTrace();
40             }
41         }
42         
43         System.out.println("剩余: "+ storage.size()+ ",Time: " +((LinkedList<?>)storage).poll());  
44         notifyAll();//喚醒在等待操作資源的線程(隊列)  
45     }    
46 }

 

 1 /**
 2  * 生產者
 3  * @author ycchia
 4  *
 5  */
 6 public class Producer implements Runnable {
 7     
 8     //倉儲模型
 9     private EventStorage storage;
10 
11     //構造函數
12     public Producer(EventStorage storage) {
13         this.storage = storage;
14     }
15 
16     @Override
17     public void run() {
18         for (int i = 0; i < 100; i++) {
19             //調用生產方法
20             storage.set();
21         }
22     }
23 }
 1 /**
 2  * 消費者
 3  * @author ycchia
 4  *
 5  */
 6 public class Consumer implements Runnable {
 7 
 8     //倉儲模型
 9     private EventStorage storage;
10     
11     //構造函數
12     public Consumer(EventStorage storage) {
13         this.storage = storage;
14     }
15     
16     @Override
17     public void run() {
18         for (int i = 0; i < 100; i++) {
19             //調用消費方法
20             storage.get();
21         }
22     }
23 }
 1 public class TestThread {
 2 
 3     public static void main(String[] args) {
 4         
 5         EventStorage storage = new EventStorage();
 6         Producer producer = new Producer(storage);
 7         //生產者線程
 8         Thread t1 = new Thread(producer);
 9         Consumer consumer = new Consumer(storage);
10         //消費者線程
11         Thread t2 = new Thread(consumer);
12 
13         //啟動線程
14         t2.start();
15         t1.start();
16     }
17 }

啟動程序,console信息如下:

完美實現多線程同步。快去試一下吧!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM