单生产单消费者

单生产者单消费者
线程:两个—一个生产线程一个消费线程
任务:两个—一个生产任务一个消费任务
数据:一份—产品

public class Demo5 {
    public static void main(String[] args) {
        //准备数据
        Product product = new Product();
        //准备任务
        Producer producer = new Producer(product);
        Consumer consumer = new Consumer(product);
        //准备生产线程消费线程
        Thread pro = new Thread(producer);
        Thread con = new Thread(consumer);
        //开启线程
        pro.start();
        con.start();
    }
}

//创建数据类--产品
class Product {
    String name;//名字
    double price;//价格
    int number;//数量

    //标识--控制唤醒等待
    boolean flag = false;

    //准备生产
    public synchronized void  setProduce(String name,double price){
        if (flag == true){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.name = name;
        this.price = price;
        System.out.println(Thread.currentThread().getName()+"  生产了:"+this.name+"   价格:"+this.price+"  数量:"+this.number);

        number++;

        flag = !flag;
        notify();
    }
    //准备消费
    public synchronized void  getConsume(){
        if (flag == false){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(Thread.currentThread().getName()+"  消费了:"+this.name+"   价格:"+this.price);

        flag = !flag;
        notify();
    }
}

//创建生产任务
class Producer implements Runnable{
    Product product;

    public Producer(Product product) {
        this.product = product;
    }

    @Override
    public void run() {
        while (true) {
            product.setProduce("bingbing", 10);
        }
    }
}
//创建消费任务
class Consumer implements  Runnable{
    Product product;

    public Consumer(Product product) {
        this.product = product;
    }

    @Override
    public void run() {
        while (true) {
            product.getConsume();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值