//牛奶箱
public class MilkBox {
private int num;
private boolean state = false;
public synchronized void setMilk(int i) {
if(state) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
num = i;
System.out.println("已经送出第"+num+"瓶牛奶");
state = true;
notifyAll();
}
public synchronized void getMilk() {
if(!state) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("取出了第"+num+"瓶牛奶");
state = false;
notifyAll();
}
}
//送牛奶的生产者
public class Producer implements Runnable{
MilkBox box;
public Producer(MilkBox box) {
this.box= box;
}
@Override
public void run() {
for(int i = 1; i <= 5; i++) {
box.setMilk(i);
}
}
}
//拿牛奶的消费者
public class Consumer implements Runnable{
MilkBox box;
public Consumer(MilkBox box) {
this.box=box;
}
@Override
public void run() {
while(true) {
box.getMilk();
}
}
}
//测试类
public static void main(String[] args) {
MilkBox box = new MilkBox();
Producer p = new Producer(box);
Consumer c = new Consumer(box);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}