虚假唤醒

Posted loveer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了虚假唤醒相关的知识,希望对你有一定的参考价值。

简介

资源num==0:此时两个消费者线程都wait。

生产者执行num++后,唤醒了所有等待的线程。

此时这两个消费者线程抢占资源后立马执行wait之后的操作,即num--,就会出现产品为负的情况。

为了避免这种情况我们应该让wait()在while()循环中多次判断。

示例

反例:
        if(num<=0) 
            System.out.println("库存已空,无法卖货");
            try 
                this.wait();
             catch (InterruptedException e) 
                e.printStackTrace();
            
        
        System.out.println(Thread.currentThread().getName()+" : "+(num--));
        this.notifyAll();


正例:
        while(num<=0) 
            System.out.println("库存已空,无法卖货");
            try 
                this.wait();
             catch (InterruptedException e) 
                e.printStackTrace();
            
        
        System.out.println(Thread.currentThread().getName()+" : "+(num--));
        this.notifyAll();

以上是关于虚假唤醒的主要内容,如果未能解决你的问题,请参考以下文章