码迷,mamicode.com
首页 > 其他好文 > 详细

虚假唤醒

时间:2019-09-14 11:40:40      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:this   生产者   tac   getname   while   出现   wait   int   catch   

简介

资源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();

虚假唤醒

标签:this   生产者   tac   getname   while   出现   wait   int   catch   

原文地址:https://www.cnblogs.com/loveer/p/11518462.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!