生产者消费者案例中包含的类:
奶箱类(Box):定义一个成员变量,表示第x瓶奶,提供存储牛奶和获取牛奶的操作
生产者类(Producer):实现Runnable接口,重写run()方法,调用存储牛奶的操作
消费者类(Customer):实现Runnable接口,重写run()方法,调用获取牛奶的操作
测试类(BoxDemo):里面有main方法,main方法中的代码步骤如下
①创建奶箱对象,这是共享数据区域
②创建消费者创建生产者对象,把奶箱对象作为构造方法参数传递,因为在这个类中要调用存储牛奶的操作
③对象,把奶箱对象作为构造方法参数传递,因为在这个类中要调用获取牛奶的操作
④创建2个线程对象,分别把生产者对象和消费者对象作为构造方法参数传递
⑤启动线程
奶箱类:
public class Box {
//牛奶
private int milk;
//奶箱状态
private boolean state = false;
//放牛奶
public synchronized void save(int milk){
//奶箱有奶,等待拿取
if(state){
try{
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
//如果奶箱为空,生产牛奶
this.milk = milk;
System.out.println("放入第" + this.milk + "瓶牛奶");
//生产完毕,调整奶箱状态
state = true;
//唤醒其他线程
notifyAll();
}
//拿牛奶
public synchronized void get(){
if(!state){
//奶箱没牛奶,等待生产
try {
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
//奶箱有牛奶,拿牛奶
System.out.println("拿取第" + this.milk + "瓶牛奶");
//拿完牛奶,调整奶箱状态
state = false;
//唤醒其他线程
notifyAll();
}
}
消费者类:
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.save(i);
}
}
}
测试类:
public class BoxDemo {
public static void main(String[] args){
//创建奶箱对象
Box b = new Box();
//创建消费者对象
Customer c = new Customer(b);
//创建生产者对象
Producer p = new Producer(b);
//创建2个线程对象
Thread t1 = new Thread(c);
Thread t2 = new Thread(p);
//启动线程
t1.start();
t2.start();
}
}
版权声明:本文为weixin_44756334原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。