簡單生產者消費者問題:現有兩個執行緒a、b,對乙個初始值未零的數加減一的操作,不能為負數,二者必須要實現輪流操作(操作十次);
就在前不久自己也遇到了乙個這樣的問題,但是沒有考慮到的是執行緒的通訊,利用迴圈完成的輪流執行,唉~~慘,不多說了重新來!!!
再一次:高內聚低耦合前提下實現執行緒操作資源類!
資源類已經實現了,現在進行執行緒建立及對資源類進行操作;//資源類
class
resource
number++
; system.out.
println
(thread.
currentthread()
.getname()
+"\t"
+num)
;//獲取執行緒名字,並輸出當前數字
this
.notifyall()
;//執行了加一操作後,喚醒乙個等待狀態的執行緒
}public
synchronized
void
descrease()
number--
; system.out.
println
(thread.
currentthread()
.getname()
+"\t"
+num)
;this
.notifyall()
;}}
乙個比較簡單的生產者消費者問題就解決了。public
class
test
catch
(interruptedexception e)}}
,"a").
start()
;}newthread((
)->
catch
(interruptedexception e)}}
,"b").
start()
;}}
最後最重要的是,如果有問題歡迎指正!!有比較好的想法可以交流學習。謝謝~~鳴謝陽哥
執行緒間通訊 生產者消費者模型
所謂的執行緒間通訊,其實就是多個執行緒再操作同乙個資源,但是操作的動作不同。當某個執行緒進入synchronized塊後,共享資料的狀態不一定滿足該執行緒的需要,需要其他執行緒改變共享資料的狀態後才能執行,而由於當時執行緒對共享資源時獨佔的,它必須解除對共享資源的鎖定的狀態,通知其他執行緒可以使用該...
執行緒 執行緒間通訊(生產者消費者模式)
注意 1.執行緒間的通訊,共享的資料一定要有同步 塊synchronized 2.一定要有wait和notify,而且二者一定是成對出現 3.生產者和消費者的執行緒實現一定是在while true 裡面public class basket public void setempty boolean ...
生產者消費者執行緒間通訊模型
include pch.h include include include include include c stl所有的容器都不是執行緒安全 using namespace std if 0 unique lock condition variable 1.lock guard和unique l...