我期待以下示例中的第二个线程挂起,因为它等待一个没有相应通知的对象。相反,它通过了 println,大概是由于虚假唤醒。
public class Spurious {
public static void main(String[] args) {
Thread t1 = new Thread() {
public void run() {
System.out.println("Hey!");
}
};
Thread t2 = new Thread() {
public void run()
{
try {
synchronized (t1) {
t1.wait();
}
} catch (InterruptedException e) {
return;
}
System.out.println("Done.");
}
};
t1.start();
t2.start();
}
}
输出:
Hey!
Done.
另一方面,如果删除“嘿!” println 从第一个线程,第二个线程确实会挂起。这发生在 MacOS 和 Linux 上。
知道为什么吗?