主要是通過blockingqueue
、volatile
、atomicinteger
等方式來實現,保證執行緒安全和資料一致性
/**
* 高併發的生產者消費者阻塞佇列
* * volatile/cas/atomicinteger/blockingqueue/執行緒互動/原子引用
* */
public
class
myresource
/** * 生產者生產資料,將資料放入到阻塞佇列並設定超時時間,防止併發超時
* @throws interruptedexception
*/public
void
prod()
throws interruptedexception
else
// 這裡使用sleep來設定生產者每秒生產乙個,只是為了在控制台方便檢視,可以注釋
timeunit.seconds.
sleep(1
);} system.out.
println
(thread.
currentthread()
.getname()
+"\t停止");
}/**
* 消費者 消費資料,利用阻塞佇列的特性獲取資料,沒有資料的時候阻塞獲取
** @throws interruptedexception
*/public
void
consumer()
throws interruptedexception
system.out.
println
(thread.
currentthread()
.getname()
+"\t 消費資料"
+ data +
"成功");
}}/** * 停止生產和消費
*/public
void
stop()
}
public
class
pc_prodconsumer
catch
(interruptedexception e)},
"aa").
start()
;// 開始消費
newthread((
)->
catch
(interruptedexception e)},
"bb").
start()
;// 5秒後主執行緒停止,停止生產和消費
timeunit.seconds.
sleep(5
);system.out.
println
(thread.
currentthread()
.getname()
+"\t 停止生產和消費");
myresource.
stop()
;}}
阻塞佇列之生產者與消費者
前段時間因為專案中對生產者與消費者的需求,故整理了一下對阻塞佇列。不說了,直接上 public class blockingqueuetest public void run catch interruptedexception e public void shutdown 消費者 public s...
佇列,生產者消費者模型
from multiprocessing import process,lock import os,time,json with open user w encoding utf 8 as f dic json.dump dic,f def search with open user r enco...
生產者消費者 生產者與消費者模式
一 什麼是生產者與消費者模式 其實生產者與消費者模式就是乙個多執行緒併發協作的模式,在這個模式中呢,一部分執行緒被用於去生產資料,另一部分執行緒去處理資料,於是便有了形象的生產者與消費者了。而為了更好的優化生產者與消費者的關係,便設立乙個緩衝區,也就相當於乙個資料倉儲,當生產者生產資料時鎖住倉庫,不...