//牛奶箱类用来实现生产者和消费者的交互
public class Box {
private int milknum=0;//定义一个牛奶数量
private boolean state=false;//定义奶箱状态true表示奶箱中有牛奶
//定义一个put方法表示存放牛奶
public synchronized void put(int milknum) {
if(state){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.milknum=milknum;
System.out.println("把第"+this.milknum+"瓶牛奶送入箱中");
state=true;
notifyAll();
}
//定义一个取走牛奶的方法
public synchronized void get() {
if (state) {
System.out.println("用户把第" + this.milknum + "瓶牛奶取走了");
state=false;
notifyAll();
}
else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class BoxDemo {
public static void main(String[] args) {
Box b=new Box();
Customer c=new Customer(b);
Producer p=new Producer(b);
Thread t1=new Thread(p);
Thread t2=new Thread(c);
t1.start();
t2.start();
}
}
public class Customer implements Runnable{
private Box b;
public Customer(Box b) {
this.b=b;
}
@Override
public void run() {
while (true){
b.get();
}
}
}
public class Producer implements Runnable{
private Box b;
public Producer(Box b) {
this.b=b;
}
@Override
public void run() {
for(int i=1;i<=5;i++){
b.put(i);
}
}
}