/** * 牛奶生產問題,冷庫中須要同時存放牛奶和發酵劑,因此固定讓牛奶數量不超過70份 發酵劑數量不超過30份 */ public class Milk { private int MAX_NUM = 0;//存放牛奶 private double MAX_NUM_MILK = 0;//存放發酵劑 public synchronized void build(int i){//生產10份牛奶 if(MAX_NUM < 70 && MAX_NUM_MILK >= 0.5){//只有當冷庫中的牛奶存量不大於70而且發酵劑數量大於1時生產 System.out.println("生產了第" +(i+1)+ "份"); MAX_NUM_MILK = MAX_NUM_MILK - 0.5; MAX_NUM = MAX_NUM + 1; this.notify(); }else{ try { this.wait();//庫存不足,不生產 } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void send(int i){//每次運輸一份牛奶 if(MAX_NUM > 0){ System.err.println("運輸了"+i+"份"); MAX_NUM = MAX_NUM - 1; this.notify(); }else{ try { this.wait();//沒有存量,不運輸 } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void buildData(int i){ System.err.println("CM:"+MAX_NUM_MILK); if(MAX_NUM_MILK < 30){ System.err.println("生產了第"+i+"份發酵劑"); MAX_NUM_MILK = MAX_NUM_MILK + 1; this.notify(); }else{ try { this.wait();//庫存容量不夠,不生產 } catch (InterruptedException e) { e.printStackTrace(); } } } }
public class Main { public static void main(String[] args) { Milk milk = new Milk(); new Thread(new Runnable() { @Override public void run() { for(int i=0;i<50;i++){ milk.buildData(i); } } }).start(); new Thread(new Runnable() { @Override public void run() { for(int i=0;i<100;i++){ milk.build(i); } } }).start(); new Thread(new Runnable() { @Override public void run() { for(int i=0;i<100;i++){ milk.send(i+1); } } }).start(); } }