標籤:out 線程 java多線程 exce this 產品 線程等待 i++ over
package de.bvb;/** * 生產者消費者模式 * 通過 wait() 和 notify() 通訊方法實現 * */public class Test1 { public static void main(String[] args) { Godown godown = new Godown(50); for (int i = 0; i < 5; i++) { new ProducerThread(i * 10, godown).start(); new ConsumerThread(i * 10, godown).start(); } }}/** 倉庫 */class Godown { public static final int max_size = 100; // 最大庫存量 public int currentSize; // 當前庫存 public Godown(int currentSize) { this.currentSize = currentSize; } // 生產指定數量的產品 public synchronized void produce(int size) { try { while (currentSize + size > max_size) { // 不滿足生產的條件 System.out.println("要生產的產品數量" + size + "超過剩餘庫容量" + (max_size - currentSize) + ",暫時不能執行生產任務!"); // 當前的生產線程等待 wait(); } // 滿足生產條件,則進行生產,這裡簡單的更改當前庫存量 currentSize += size; System.out.println("生產前倉儲量為:" + (currentSize - size) + ";生產了" + size + "個產品,現倉儲量為" + currentSize); // 喚醒在此對象監視器上等待的所有線程 notifyAll(); } catch (Exception e) { e.printStackTrace(); } } // 消費指定數量的產品 public synchronized void consume(int size) { try { while (currentSize < size) { // 不滿足消費的條件 System.out.println("要消費的產品數量" + size + "超過剩餘庫存量" + (currentSize) + ",暫時不能執行消費任務!"); // 當前的生產線程等待 wait(); } // 滿足生產條件,則進行生產,這裡簡單的更改當前庫存量 currentSize -= size; System.out.println("消費前的倉儲量為" + (currentSize + size) + ";已經消費了" + size + "個產品,現倉儲量為" + currentSize); // 喚醒在此對象監視器上等待的所有線程 notifyAll(); } catch (Exception e) { e.printStackTrace(); } }}/** 生產者線程 */class ProducerThread extends Thread { private int size; private Godown godown; public ProducerThread(int size, Godown godown) { super(); this.size = size; this.godown = godown; } @Override public void run() { godown.produce(size); }}class ConsumerThread extends Thread { private int size; private Godown godown; public ConsumerThread(int size, Godown godown) { super(); this.size = size; this.godown = godown; } @Override public void run() { godown.consume(size); }}
java多線程 生產者消費者模式