生產者消費者步驟示例

2021-10-08 14:33:59 字數 2140 閱讀 5464

生產者消費者**示例synchronized

/**

* 執行緒之間通訊

* 生產者消費者問題

* 四個步驟:判斷,等待,業務,通知

*/public

class

acatch

(interruptedexception e)}}

,"a").

start()

;new

thread((

)->

catch

(interruptedexception e)}}

,"b").

start()

;}}class

data

//3、業務

num++

;//4、通知

system.out.

println

(thread.

currentthread()

.getname()

+"=>"

+num)

;this

.notifyall()

;}public

synchronized

void

decrement()

throws interruptedexception

num--

; system.out.

println

(thread.

currentthread()

.getname()

+"=>"

+num)

;this

.notifyall()

;}}

生產者消費者**示例lock鎖,精準喚醒

public

class

bcatch

(interruptedexception e)}}

,"a").

start()

;new

thread((

)->

catch

(interruptedexception e)}}

,"b").

start()

;new

thread((

)->

catch

(interruptedexception e)}}

,"c").

start()

;}}class

data2

//3.業務

num=2;

system.out.

println

(thread.

currentthread()

.getname()

+"=>aaaaaaa");

//4.喚醒

condition2.

signal()

;}catch

(exception e)

finally

}public

void

printb()

throws interruptedexception

num=3;

system.out.

println

(thread.

currentthread()

.getname()

+"=>bbbbbb");

condition3.

signal()

;}catch

(exception e)

finally

}public

void

printc()

throws interruptedexception

num=0;

system.out.

println

(thread.

currentthread()

.getname()

+"=>cccccc");

condition1.

signal()

;}catch

(exception e)

finally

}

生產者消費者 簡單示例

class meal public string tostring class waitperson implements runnable public void run system.out.println waitperson got restaurant.meal synchronized ...

生產者消費者示例01

編寫程式,要求子執行緒迴圈10次,接著主線程迴圈100次,接著又回到子執行緒迴圈10次,接著再回到主線程迴圈100次,如此迴圈50次 public class test02 class serviceobject catch interruptedexception e for int i 1 i ...

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

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