多线程之虚假唤醒

2 篇文章 0 订阅
class Data {
    private int number = 0;
    public synchronized void inc() throws InterruptedException {
        if(number!=0) {
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        this.notifyAll();
    }

    public synchronized void dec() throws InterruptedException {
        if(number==0) {
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        this.notifyAll();
    }
}
public class Test {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            for (int i=0; i<10; i++) {
                try {
                    data.inc();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i=0; i<10; i++) {
                try {
                    data.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
        new Thread(() -> {
            for (int i=0; i<10; i++) {
                try {
                    data.inc();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
        new Thread(() -> {
            for (int i=0; i<10; i++) {
                try {
                    data.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}

这段代码目的是让number在0和1之间来回变换。AC线程是加操作,BD线程是减操作。
但是实际的结果却是:
A=>1D=>0C=>1B=>0C=>1B=>0C=>1B=>0C=>1B=>0C=>1B=>0C=>1B=>0C=>1B=>0C=>1B=>0C=>1B=>0
C=>1
B=>0
D=>-1
D=>-2
D=>-3
D=>-4
D=>-5
D=>-6
D=>-7
D=>-8
D=>-9
A=>-8
结果从中间开始就变得诡异。
原因是CPU有几率会进行虚假唤醒。
虚假唤醒指的是wait中的线程在没有被notify的情况下苏醒,而这种虚假唤醒是从wait方法后继续执行。
而虚假唤醒产生的原因是为了不减慢条件变量操作的效率,没有保证线程每次的唤醒都由notify触发
所以这个例子中当D线程被虚假唤醒后不用经过if判断,直接进行了–操作。
改进方法是将if换为while。这样即使虚假唤醒,仍要进行判断后wait。

总结:线程中只要是wait的操作,都要用while代替if

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值