Java如何通過線程解決生產(chǎn)者/消費者問題
生產(chǎn)者和消費者問題是線程模型中的經(jīng)典問題:生產(chǎn)者和消費者在同一時間段內(nèi)共用同一個存儲空間,如下圖所示
生產(chǎn)者向空間里存放數(shù)據(jù),而消費者取用數(shù)據(jù),如果不加以協(xié)調(diào)可能會出現(xiàn)以下情況:
存儲空間已滿,而生產(chǎn)者占用著它,消費者等著生產(chǎn)者讓出空間從而去除產(chǎn)品,生產(chǎn)者等著消費者消費產(chǎn)品,從而向空間中添加產(chǎn)品。互相等待,從而發(fā)生死鎖。
以下實例演示了如何通過線程解決生產(chǎn)者/消費者問題:
/* author by javaidea.com ProducerConsumerTest.java */public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); }}class CubbyHole { private int contents; private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notifyAll(); return contents; } public synchronized void put(int value) { while (available == true) { try { wait(); } catch (InterruptedException e) { } } contents = value; available = true; notifyAll(); }}class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(); System.out.println('消費者 #' + this.number+ ' got: ' + value); } }}class Producer extends Thread { private CubbyHole cubbyhole; private int number; public Producer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { for (int i = 0; i < 10; i++) { cubbyhole.put(i); System.out.println('生產(chǎn)者 #' + this.number + ' put: ' + i); try { sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } } }}
以上代碼運行輸出結(jié)果為:
消費者 #1 got: 0生產(chǎn)者 #1 put: 0生產(chǎn)者 #1 put: 1消費者 #1 got: 1生產(chǎn)者 #1 put: 2消費者 #1 got: 2生產(chǎn)者 #1 put: 3消費者 #1 got: 3生產(chǎn)者 #1 put: 4消費者 #1 got: 4生產(chǎn)者 #1 put: 5消費者 #1 got: 5生產(chǎn)者 #1 put: 6消費者 #1 got: 6生產(chǎn)者 #1 put: 7消費者 #1 got: 7生產(chǎn)者 #1 put: 8消費者 #1 got: 8生產(chǎn)者 #1 put: 9消費者 #1 got: 9
以上就是Java如何通過線程解決生產(chǎn)者/消費者問題的詳細內(nèi)容,更多關(guān)于Java 解決生產(chǎn)者/消費者問題的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Python如何批量生成和調(diào)用變量2. ASP.NET MVC實現(xiàn)橫向展示購物車3. 通過CSS數(shù)學函數(shù)實現(xiàn)動畫特效4. ASP.Net Core對USB攝像頭進行截圖5. Python獲取B站粉絲數(shù)的示例代碼6. .net如何優(yōu)雅的使用EFCore實例詳解7. windows服務器使用IIS時thinkphp搜索中文無效問題8. ajax動態(tài)加載json數(shù)據(jù)并詳細解析9. python實現(xiàn)自冪數(shù)的示例代碼10. python利用opencv實現(xiàn)顏色檢測
