Java如何通過線程解決生產者/消費者問題
生產者和消費者問題是線程模型中的經典問題:生產者和消費者在同一時間段內共用同一個存儲空間,如下圖所示
生產者向空間里存放數據,而消費者取用數據,如果不加以協調可能會出現以下情況:
存儲空間已滿,而生產者占用著它,消費者等著生產者讓出空間從而去除產品,生產者等著消費者消費產品,從而向空間中添加產品。互相等待,從而發生死鎖。
以下實例演示了如何通過線程解決生產者/消費者問題:
/* 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('生產者 #' + this.number + ' put: ' + i); try { sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } } }}
以上代碼運行輸出結果為:
消費者 #1 got: 0生產者 #1 put: 0生產者 #1 put: 1消費者 #1 got: 1生產者 #1 put: 2消費者 #1 got: 2生產者 #1 put: 3消費者 #1 got: 3生產者 #1 put: 4消費者 #1 got: 4生產者 #1 put: 5消費者 #1 got: 5生產者 #1 put: 6消費者 #1 got: 6生產者 #1 put: 7消費者 #1 got: 7生產者 #1 put: 8消費者 #1 got: 8生產者 #1 put: 9消費者 #1 got: 9
以上就是Java如何通過線程解決生產者/消費者問題的詳細內容,更多關于Java 解決生產者/消費者問題的資料請關注好吧啦網其它相關文章!
相關文章: