水能zai舟 2021-05-21 10:44 采纳率: 50%
浏览 69

以下代码产生死锁的原因是什么?

以下是一个生产者与消费者的DEMO,但是运行过程中出现死锁,请问原因是什么?

Production类:

@Data
public class Production {

    private int id;

    private boolean flag;

    public Production() {
        id = 0;
        flag = false;
    }
    
}

 

生产者类:

public class Productor {

    private Production production;

    public Productor(Production production) {
        this.production = production;
    }

    public synchronized void product() {
        if (!production.isFlag()) {

            production.setId(production.getId() + 1);
            System.out.println(Thread.currentThread().getName() + "product第: " + production.getId());

            production.setFlag(!production.isFlag());
            notifyAll();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


消费者类:

public class Consumer {
    private Production production;

    public Consumer(Production production) {
        this.production = production;
    }

    public synchronized void consume() {

        if (production.isFlag()) {

            System.out.println(Thread.currentThread().getName() + "consume第: " + production.getId());

            production.setFlag(!production.isFlag());
            notifyAll();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

 

跑起来:
 

public class ThreadTest {

    public static void main(String[] args) {

        Production production = new Production();
        Productor productor = new Productor(production);
        Consumer consumer = new Consumer(production);

        new Thread(() -> {
            for (int i = 0; i < 100; i ++ ) productor.product();
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 100; i ++ ) consumer.consume();
        }).start();
   }

 

结果:

Thread-0product第: 1
Thread-1consume第: 1



...没有下文了
  • 写回答

1条回答 默认 最新

  • benbenli 2021-05-21 11:18
    关注

    生产者消费者的synchronized函数互相并没有互斥操作production的作用。生产者和消费者的函数都不加synchronized,二改为都 synchronized(production) 吧。

    另外 Boolean类型的读写不一定是原子操作,不宜作为进入互斥的方法。synchronized(production)可以。

     

     

    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)