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

以下是一个生产者与消费者的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



...没有下文了

 

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

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