多生产多消费者&死锁

package com.qf.test;

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

生产任务与消费任务共用一个数据–产品类

要求:最终也要实现一次生产一次消费
错误描述:当有两个生产线程,两个消费线程同时存在的时候,有可能出现生产一次,消费多次或者生产多次消费一次的情况.
原因:当线程被重新唤醒之后,没有判断标记,直接执行了下面的代码

解决办法:将标记处的if改成while
*
*问题描述:继续运行程序,会出现死锁的情况(4个线程同时处于等待状态)
*原因:唤醒的是本方的线程,最后导致所有的线程都处于等待状态.
*
*解决办法:将notify改成notifyAll.保证将对方的线程唤醒
*
*死锁:出现的情况有两种
*1.所有的线程处于等待状态
*2.锁之间进行嵌套调用

*/
public class Demo6 {
public static void main(String[] args) {
//准备数据
Product1 product = new Product1();
//准备任务
Producer1 producer = new Producer1(product);
Consumer1 consumer = new Consumer1(product);
//准备生产线程消费线程
Thread pro1 = new Thread(producer);
Thread pro2 = new Thread(producer);
Thread con1 = new Thread(consumer);
Thread con2 = new Thread(consumer);
//开启线程
pro1.start();
con1.start();
pro2.start();
con2.start();
}
}

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

//标识--控制唤醒等待
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;
    System.out.println(Thread.currentThread().getName()+"  生产了:"+this.name+"   价格:"+this.price+"  数量:"+this.number);

    number++;

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

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

    flag = !flag;
    //notify();
    notifyAll();
}

}

//创建生产任务
class Producer1 implements Runnable{
Product1 product;

public Producer1(Product1 product) {
    this.product = product;
}

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

}

//创建消费任务
class Consumer1 implements Runnable{
Product1 product;

public Consumer1(Product1 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、付费专栏及课程。

余额充值