程序出现死锁了,为什么?


public class Test {
    private Object mutex = new Object();
    private volatile boolean isEmpty = true;
    private volatile boolean isFull = false;
    private String buffer = null;

    public static void main(String[] args) {
        new Test().start();
    }

    public void start() {
        Thread consumer = new Thread(new Consumer(mutex));
        Thread producer = new Thread(new Producer(mutex));
        consumer.start();
        producer.start();
    }

    class Producer implements Runnable {

        private Object mutex = null;

        public Producer(Object mutex) {
            this.mutex = mutex;
        }

        @Override
        public void run() {
            int count = 0;
            while (true) {
                while (isFull) {
                    try {
                        synchronized (mutex) {
                            mutex.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                buffer = "" + ++count;
                System.out.println(Thread.currentThread().getName() + " produce " + buffer);
                isFull = true;
                isEmpty = false;
                synchronized (mutex) {
                    mutex.notifyAll();
                }
            }
        }
    }

    class Consumer implements Runnable {
        private Object mutex = null;

        public Consumer(Object mutex) {
            this.mutex = mutex;
        }

        @Override
        public void run() {
            while (true) {
                while (isEmpty) {
                    try {
                        synchronized (mutex) {
                            mutex.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + " consume " + buffer);
                buffer = null;
                isEmpty = true;
                isFull = false;
                synchronized (mutex) {
                    mutex.notifyAll();
                }
            }
        }
    }
}

出现死锁,是个什么情况。。。。。。

你这写的就是一个死锁,当Consumer释放锁之后Producer执行,Producer唤醒Consumer,而Producer又进入循环然后处于等待状态,

循环下去肯定是死锁的,即使你produce设置成有界的,依然是死锁,因为Consumer处于等待的状态