java多线程经典问题四--多生产者多消费者问题

多生产者多消费者:
两个生产线程,两个消费线程
两个任务:生产任务,消费任务
一份数据

public class Demo5 {
    public static void main(String[] args) {
        //1.准备数据
        Product1 product = new Product1();
        //2.创建生产消费任务
        Produce1 produce = new Produce1(product);
        Consume1 consume = new Consume1(product);
        //3.创建生产线程
        Thread thread0 = new Thread(produce);
        Thread thread2 = new Thread(consume);
        Thread thread1 = new Thread(produce);
        Thread thread3 = new Thread(consume);
        //4.开启线程
        thread0.start();
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

//数据类
class Product1{
    String name;
    double price;
    int count=0;

    //标识
    boolean flag = false;

    //准备生产
    public synchronized void setProduce(String name, double price) {
         while(flag == true) {
             try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
         }
         this.name = name;
         this.price = price;
         count ++;
         System.out.println(Thread.currentThread().getName()+"生产了:" + name+"  产品数量:"+count+"  价格"+price);
         flag = !flag;
         notifyAll();
    }
    //准备消费
    public synchronized void getProduce() {
        while(flag == false) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName()+"消费了:" + name+"  产品数量:"+count+"  价格"+price);
        flag = !flag;
        notifyAll();
    }
}
//生产任务
class  Produce1 implements Runnable{

    Product1 product;

    public Produce1(Product1 product) {
        super();
        this.product = product;
    }

    @Override
    public void run() {
        while(true) {
            product.setProduce("bingbing", 10);
        }
    }
}

//消费任务
class  Consume1 implements Runnable{
    Product1 product;

    public Consume1(Product1 product) {
        super();
        this.product = product;
    }


    @Override
    public void run() {
        while(true) {
            product.getProduce();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值