测试类
public class Test {
public static void main(String[] args) {
//创建公共资源
Box b = new Box();
//创建生产者对象,并将公共奶箱资源作为参数传递
Producer p = new Producer(b);
//同样创建消费者对象
Customer c = new Customer(b);
//创建两个对象对应的线程
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
//启动线程
t1.start();
t2.start();
}
}
生产者类
public class Producer implements Runnable {
//创建奶箱成员变量,为后续对共享数据的操作做准备
private Box b = new Box();
//创建带参构造,方便将共享资源传入
public Producer(Box b) {
this.b = b;
}
//重写run()方法,实现不停调用放牛奶操作
@Override
public void run() {
for (int i = 1; i < 30; i++) {
b.put(i);
}
}
}
消费者类
public class Customer implements Runnable{
private Box b = new Box();
public Customer(Box b) {
this.b = b;
}
@Override
public void run() {
while (true){
b.get();
}
}
}
奶箱类,即公共资源
package milkThread;
public class Box {
private int milk;
//判断奶箱中是否有牛奶的状态参数
private boolean state = false;
// sleep()方法和notify()方法一般配合synchronized同步代码块使用 ,不然会报错
public synchronized void put(int milk){
//若奶箱中还有牛奶,则等待
if (state){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//没有牛奶则执行放入牛奶操作,并将奶箱状态重置,并且唤醒另外一个线程
this.milk = milk;
System.out.println("放入第"+this.milk+"瓶奶");
state = true;
notify();
}
public synchronized void get(){
if (!state){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("拿出第"+this.milk+"瓶奶");
state =false;
notify();
}
}