生產者與消費者問題

2022-01-14 00:33:15 字數 904 閱讀 5513

知識點:生產者與消費者問題

涉及到的執行緒間通訊的方法

wait():當前執行緒掛起並放棄cpu,同步資源,使別的執行緒可訪問並修改共享資源,當前執行緒排隊等候再次對資源訪問

notify():喚醒正在排隊等待同步資源的執行緒中優先順序最高者結束等待

notifyall():喚醒正在排隊等待資源的所有執行緒結束等待

場景

生產者(producer)生產產品,送到店員(clerk)那裡,消費者(customer)從店員那裡取走產品,店員只能持有一定數量的產品(如:20),如果店員那裡已經有了20個產品,店員會通知生產者停一下(wait()),店中有空位置放產品時,通知生產者繼續生產,如果店員那裡沒有產品了,會通知消費者等一下,店中有產品了,通知消費者繼續消費。

例項

class clerk else  catch (interruptedexception e) }}

public synchronized void consumeproduct()else catch (interruptedexception e) }}

}class producer implements runnable

@override

public void run() }}

class consumer implements runnable

@override

public void run() }}

測試類

public class test 

}

執行部分結果截圖:

生產者消費者 生產者與消費者模式

一 什麼是生產者與消費者模式 其實生產者與消費者模式就是乙個多執行緒併發協作的模式,在這個模式中呢,一部分執行緒被用於去生產資料,另一部分執行緒去處理資料,於是便有了形象的生產者與消費者了。而為了更好的優化生產者與消費者的關係,便設立乙個緩衝區,也就相當於乙個資料倉儲,當生產者生產資料時鎖住倉庫,不...

生產者與消費者問題

使用synchronized同步鎖機制,執行緒先獲得物件的鎖,先上鎖後執行執行緒內容,執行完成後釋放鎖。使用wait 和notifyall 簡單實現生產者與消費者 public class test1 class producer implements runnablecatch interrupt...

生產者消費者問題

public class producer consumer class godown public godown int num public synchronized void produce int n catch interruptedexception e curr num n syste...