生产者和消费者的理解
生活随笔
收集整理的這篇文章主要介紹了
生产者和消费者的理解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
生產者和消費者用ReentrantLock+Condtion來實現
首先創建線程池來創建兩個線程,然后分配相應的任務,生產者線程負責生產,消費者線程負責消費。為了讓生產者和消費者之間解耦,有相關隊列進行數據的存放。當隊列為空或者滿的時候,消費者/生產者線程等待,并且釋放鎖,自己處于等待狀態。當隊列中添加或者減少一個資源的時候,消費者/生產者線程會被喚醒,同時放棄鎖,自己處于等待狀態。
代碼可以通過synchronized來鎖著相應的隊列對象,或者使用ReentrantLock+Condtion來進行操作。
必要條件,ReentrantLock、Condtion、Queuq、ThreadProducer、ThreadConsumer、ExecutorService
public class ProducerConsumer{public static final int cap=1;private static Buffer buffer =new Buffer();public static void main(String args[]){//創建線程池ExecutorService service = Executors.newFixedThreadPool(2);service.execute(new Producer());service.execute(new Consumer());service.shutdown();}public static class Producer implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubtry {int i=1;while(true) {System.out.println("生產者寫入"+i);buffer.write(i++);Thread.sleep(new Random().nextInt(1000));}} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public static class Consumer implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubtry {while(true) {System.out.println("消費者讀取"+buffer.read());Thread.sleep(new Random().nextInt(1000));}} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public static class Buffer{private static final Lock lock = new ReentrantLock();private static final Condition fullCondition = lock.newCondition(); private static final Condition emptyCondition = lock.newCondition();Queue<Integer> queue = new LinkedList<Integer>();public void write(int i) {// TODO Auto-generated method stublock.lock();try {while(queue.size()==cap) {System.out.println("生產者停止生產,等待非滿喚醒");fullCondition.await();}queue.offer(i);System.out.println("生產者進行生產,生產了"+i);emptyCondition.signal();}catch(InterruptedException e) {}finally {lock.unlock();}}public int read() {int value=0;lock.lock();try {while(queue.isEmpty()) {System.out.println("消費者停止消費,等待非空喚醒");emptyCondition.await();}value=queue.remove();System.out.println("消費者進行消費,消費了"+value);fullCondition.signal();}catch(InterruptedException e) {}finally {lock.unlock();}return value;} }}輸出結果:
生產者寫入1 生產者進行生產,生產了1 消費者進行消費,消費了1 消費者讀取1 消費者停止消費,等待非空喚醒 生產者寫入2 生產者進行生產,生產了2 消費者進行消費,消費了2 消費者讀取2 消費者停止消費,等待非空喚醒 生產者寫入3 生產者進行生產,生產了3 消費者進行消費,消費了3 消費者讀取3 消費者停止消費,等待非空喚醒 生產者寫入4 生產者進行生產,生產了4 消費者進行消費,消費了4 消費者讀取4 消費者停止消費,等待非空喚醒 生產者寫入5 生產者進行生產,生產了5 消費者進行消費,消費了5 消費者讀取5 消費者停止消費,等待非空喚醒 生產者寫入6 生產者進行生產,生產了6 消費者進行消費,消費了6 消費者讀取6總結
以上是生活随笔為你收集整理的生产者和消费者的理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【C语言】对拍【保姆级教程】
- 下一篇: 微信小程序 获取手机号码详解