多线程下虚假唤醒问题

背景

一个生产者,两个消费者;生产者对数值加1,当大于0时消费者进行消费,每次减去1.按道理来讲数值最小为0,但是实际运行时会出现负数。

原因,消费代码导致

/**
* 分析:消费者1得到执行,会进入wait状态,此时数值为0;然后生产者得到执行,数值变为1;消费2线程得到执行,数值变为0;
*  紧接着,消费1线程得到执行,此时不会重新判断数值,会接着继续往下执行,就是变为-1.
*/
public synchronized void sub(){
        try {
            if (num == 0){//解决办法:此处有问题,if改为while
                System.out.println(Thread.currentThread().getName());
                this.wait();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+":"+num);
            this.notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
        }

    }
原文地址:https://www.cnblogs.com/xingrui/p/13401259.html