JavaSE:執行緒 - 生產者與消費者模型
阿新 • • 發佈:2021-06-21
1. 圖解
2. 程式碼示例
<1> 倉庫類
1 public class StoreHouse { 2 private int cnt = 0; // 用於記錄產品的數量 3 4 public synchronized void produceProduct() { 5 notify(); 6 if (cnt < 10) { 7 System.out.println("執行緒" + Thread.currentThread().getName() + "正在生產第" + (cnt+1) + "個產品...");8 cnt++; 9 } else { 10 try { 11 wait(); 12 } catch (InterruptedException e) { 13 e.printStackTrace(); 14 } 15 } 16 } 17 18 public synchronized void consumerProduct() { 19 notify(); 20 if(cnt > 0) { 21 System.out.println("執行緒" + Thread.currentThread().getName() + "消費第" + cnt + "個產品"); 22 cnt--; 23 } else { 24 try { 25 wait(); 26 } catch (InterruptedException e) { 27 e.printStackTrace(); 28 }29 } 30 } 31 }
<2> 生產者執行緒
3 /** 4 * 程式設計實現生產者執行緒,不斷地生產產品 5 */ 6 public class ProduceThread extends Thread { 7 // 宣告一個倉庫型別的引用作為成員變數,是為了能呼叫呼叫倉庫類中的生產方法 合成複用原則 8 private StoreHouse storeHouse; 9 // 為了確保兩個執行緒共用同一個倉庫 10 public ProduceThread(StoreHouse storeHouse) { 11 this.storeHouse = storeHouse; 12 } 13 14 @Override 15 public void run() { 16 while (true) { 17 storeHouse.produceProduct(); 18 try { 19 Thread.sleep(1000); 20 } catch (InterruptedException e) { 21 e.printStackTrace(); 22 } 23 } 24 } 25 }
<3> 消費者執行緒
1 public class ConsumerThread extends Thread { 2 // 宣告一個倉庫型別的引用作為成員變數,是為了能呼叫呼叫倉庫類中的生產方法 合成複用原則 3 private StoreHouse storeHouse; 4 // 為了確保兩個執行緒共用同一個倉庫 5 public ConsumerThread(StoreHouse storeHouse) { 6 this.storeHouse = storeHouse; 7 } 8 9 @Override 10 public void run() { 11 while (true) { 12 storeHouse.consumerProduct(); 13 try { 14 Thread.sleep(100); 15 } catch (InterruptedException e) { 16 e.printStackTrace(); 17 } 18 } 19 } 20 }
<4> StoreHouseTest.java
public class StoreHouseTest { public static void main(String[] args) { // 建立倉庫類的物件 StoreHouse storeHouse = new StoreHouse(); // 建立執行緒類物件並啟動 ProduceThread t1 = new ProduceThread(storeHouse); ConsumerThread t2 = new ConsumerThread(storeHouse); t1.start(); t2.start(); } }