執行緒互動 生產消費模型

2022-04-01 08:33:04 字數 1385 閱讀 4329

這個例子利用執行緒的wait(),notify(),以及同步和鎖來實現,主要為了加深方法和互動理解,簡單介紹:

1.倉儲初始100

2.隨機生產或消費,大於90時不生產,小於20時不消費

3.無限執行

package

timeinterval;

public

class

initnum

} else}}

}}class producer implements

runnable

else

try

catch

(interruptedexception e)

system.out.println("go on...");

notify();}}

}class customer implements

runnable

else

try

catch

(interruptedexception e)

system.out.println("go on...");

notify();}}

}

執行結果:

init num : 100current num : 100begin to produce...

producing...

cannot produce...

go on...

stop produce

current num : 100begin to produce...

producing...

cannot produce...

go on...

stop produce

current num : 100begin to consume...

consuming...

consume num - : 9.0go on...

stop consume

current num : 91begin to consume...

consuming...

consume num - : 20.0go on...

stop consume

current num : 71begin to consume...

consuming...

consume num - : 5.0go on...

stop consume

current num : 66begin to produce...

producing...

produce num + : 6.0

生產時間定為5s,避免notify() 執行在前,wait()執行在後的情況發生

多執行緒 單生產單消費模型

建立資源物件,提供儲存和取出方法 使用synchronized 塊實現 created by shaoqinghua on 2018 5 3.定義乙個負責儲存和取出的資源類 public class resource catch interruptedexception e objs 0 obj s...

linux 執行緒(生產設消費者模型)

include include include include using namespace std define max queue 10 class blockqueue blockqueue 析構函式中將乙個鎖和兩個條件變數 生產者條件變數,消費者條件變數 銷毀 bool blockqueu...

執行緒,生產者消費者模型

什麼是執行緒 1.執行緒是cpu最小的執行單位 2.程序是資源單位 3.如果將作業系統比作工廠的話,程序是車間,執行緒是流水線,而cpu為電源 開啟乙個程序預設有乙個執行緒即主線程 執行緒的兩種開啟方式 例項化thread類 自定義mythread類,繼承thread類,覆蓋run方法 什麼時候需要...