package it.CP;
public class boxMilk {
private int box;
//定义一个成员变量表示奶箱的状态
private boolean state = false;
public synchronized void put(int box) {
//如果有牛奶,则需要等待
if (state) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有则放入牛奶
this.box = box;
System.out.println("生产者放入第" + box + "瓶奶");
//生产完毕后,修改奶箱的状态
state = true;
//唤醒其他等待的线程
notifyAll();
}
public synchronized void get() {
//如果没牛奶,则需要等待放入牛奶
if(!state){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果有牛奶,则需要拿走
System.out.println("消费者拿掉第" + box + "瓶奶");
//消费完后,需要修改奶箱状态
state = false;
//唤醒其他等待的线程
notifyAll();
}
}
package it.CP;
public class Producer implements Runnable {
private boxMilk b;
public Producer(boxMilk b) {
this.b = b;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
b.put(i);
}
}
}
package it.CP;
public class Customer implements Runnable {
private boxMilk b;
public Customer(boxMilk b) {
this.b = b;
}
@Override
public void run() {
while (true) {
b.get();
}
}
}
package it.CP;
public class test {
public static void main(String[] args) {
//创建奶箱对象,这是共享数据区域
boxMilk b = new boxMilk();
//创建生产者对象,把奶箱对象作为构造方法参数传递,因为在这个类中要调用存储牛奶的操作
Producer p = new Producer(b);
//创建生产者对象,把奶箱对象作为构造方法参数传递,因为在这个类中要调用获取牛奶的操作
Customer c = new Customer(b);
//创建2个线程对象,分别把生产者和消费者对象作为构造方法参数传递
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
//启动线程
t1.start();
t2.start();
}
}