天天看点

多线程之虚假唤醒

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