java多執行緒生產者消費者模型
阿新 • • 發佈:2022-02-20
java多執行緒生產者消費者模型
利用緩衝區解決:管理法
程式碼
// 生產者,消費者,產品,緩衝區 public class TestPCDemo { public static void main(String[] args) { // 定義容器 SynContainer synContainer = new SynContainer(); // 生產者執行緒 Thread pThread = new Thread(new Producer(synContainer)); // 消費者執行緒 Thread cThread = new Thread(new Consumer(synContainer)); // 開啟執行緒 pThread.start(); cThread.start(); } } // 生產者 class Producer implements Runnable { // 容器 SynContainer container; // 構造器 public Producer(SynContainer container) { this.container = container; } // 生產方法 @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("生產了第" + i + "個產品"); container.addProduction(new Production(i)); } } } // 消費者 class Consumer implements Runnable { // 容器 SynContainer container; // 構造器 public Consumer(SynContainer container) { this.container = container; } // 消費方法 @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("消費了第" + container.popProduction().id + "個產品"); } } } // 產品 class Production { // 編號 public int id; public Production(int id) { this.id = id; } } // 緩衝區 class SynContainer { // 需要一個容器大小 Production[] productions = new Production[10]; // 容器計數器 int count = 0; // 生產者放入產品 public synchronized void addProduction(Production p) { // 如果容器滿了,需要等待消費者消費 if (count == productions.length) { // 通知消費者,生產等待 try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 如果沒滿就生產 productions[count] = p; ++count; // 有產品就可以通知消費者消費了 this.notifyAll(); } // 消費者消費產品 public synchronized Production popProduction() { // 如果容器沒有,需要等待生產者生產 if (count == 0) { // 通知生產者,消費等待 try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 如果有就消費 --count; Production production = productions[count]; // 通知生產 this.notifyAll(); // 看看消費的是什麼 return production; } }