Java多執行緒之 使用wait和notify實現生產者消費者模型
阿新 • • 發佈:2019-01-12
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
在多執行緒開發中,最經典的一個模型就是生產者消費者模型,他們有一個緩衝區,緩衝區有最大限制,當緩衝區滿
的時候,生產者是不能將產品放入到緩衝區裡面的,當然,當緩衝區是空的時候,消費者也不能從中拿出來產品,這就
涉及到了在多執行緒中的條件判斷,java為了實現這些功能,提供了wait和notify方法,他們可以線上程不滿足要求的時候
讓執行緒讓出來資源等待,當有資源的時候再notify他們讓他們繼續工作,下面我們用實際的程式碼來展示如何使用wait和
notify來實現生產者消費者這個經典的模型。
首先是緩衝區的實現,我們使用LinkedList來代替
package com.bird.concursey.charpet2;import java.util.Date;import java.util.LinkedList;import java.util.List;public class EventStorage { private int maxSize; private List<Date> storage; public EventStorage() { maxSize = 10; storage = new LinkedList<Date>(); } public synchronized void set() { while(storage.size() == maxSize) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } storage.add(new Date()); System.out.printf("Set: %d",storage.size()); notifyAll(); } public synchronized void get() { while(storage.size() == 0) { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.printf("Get: %d: %s",storage.size(),((LinkedList<?>)storage).poll()); notifyAll(); }}
然後就是生產者和消費者
package com.bird.concursey.charpet2;public class Producer implements Runnable { private EventStorage storge; public Producer(EventStorage storage) { this.storge = storage; } @Override public void run() { for(int i = 0; i < 100; i++) { storge.set(); } }}
package com.bird.concursey.charpet2;public class Consumer implements Runnable { private EventStorage storage; public Consumer(EventStorage storage) { this.storage = storage; } @Override public void run() { for(int i = 0; i < 100; i++) { storage.get(); } } public static void main(String[] args) { EventStorage storage = new EventStorage(); Producer producer = new Producer(storage); Thread thread1 = new Thread(producer); Consumer consumer = new Consumer(storage); Thread thread2 = new Thread(consumer); thread2.start(); thread1.start(); }}
可以看到,這裡面就是用了wait和notifyall方法實現了生產者消費方法,具體的執行過程大家可以通過閱讀程式碼來體
會,還是很直觀的。