package 多线程.生产者消费者模式2;publicclassMilkBox{privateint milk;// state 表示奶箱状态,空的话为 false,非空为 trueprivateboolean state =false;// 要对 put 和 get 方法实现线程同步安全publicsynchronizedvoidput(int milk){if(state){try{wait();}catch(InterruptedException e){
e.printStackTrace();}}this.milk = milk;System.out.println("送奶工将第"+this.milk+"瓶奶放入奶箱");
state =true;// 唤醒其他等待的线程notifyAll();}publicsynchronizedvoidget(){if(!state){try{wait();}catch(InterruptedException e){
e.printStackTrace();}}System.out.println("用户拿到第"+this.milk +"瓶奶");
state =false;notifyAll();}}
主程序代码
package 多线程.生产者消费者模式2;import 多线程.消费者生产者模式.Milk;importjavax.swing.*;importjava.beans.Customizer;publicclassDemo{publicstaticvoidmain(String[] args){MilkBox b =newMilkBox();Producer p =newProducer(b);Consumer c =newConsumer(b);Thread t1 =newThread(p);Thread t2 =newThread(c);
t1.start();
t2.start();}}