假唤醒是程序的错误,指不应该被唤醒却被唤醒了。
package com.concurenny.chapter.eight;
import java.util.ArrayList;
import java.util.List;
/**
* 创建者:Mr lebron 创建时间:2017年11月17日 下午4:48:11
*/
public class FakeWakeUp {
private static List<String> lists = new ArrayList<>();
public static void main(String[] args) {
// 消费资源,没有资源执行wait方法
new Thread(() -> {
pop();
}).start();
new Thread(() -> {
pop();
}).start();
new Thread(() -> {
pop();
}).start();
push("1");
}
public synchronized static String pop() {
if (lists.size() <= 0) { //if -> while
try {
// 等待资源进来才能有资源可用
System.out.println("wait 前");
FakeWakeUp.class.wait();
System.out.println("wait 后");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
FakeWakeUp.class.notifyAll();
// 这里很可能出现假唤醒,就会空指针异常.
// 因为notifyAll被调用,所有线程唤醒,只差获取锁就能执行了,当pop线程执行remove之后,lists大小为0,然而所有的pop线程此时都拥有CPU执行权的,并不需要notify,所以空指针异常。
// 可以将if改为while不停地判断是否还能pop,不能就执行wait来避免假唤醒。
return lists.remove(lists.size() - 1);
}
public synchronized static String push(String x) {
lists.add(x);
System.out.println("notifyAll 前");
// 唤醒其他线程可以消费了
FakeWakeUp.class.notifyAll();
System.out.println("notifyAll 后");
return x;
}
}