/** * 牛奶生产问题,冷库中须要同时存放牛奶和发酵剂,因此固定让牛奶数量不超过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(); } }