我期待以下示例中的第二个线程挂起,因为它等待没有相应通知的对象.相反,它落到了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();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Hey!
Done.
Run Code Online (Sandbox Code Playgroud)
另一方面,如果删除"嘿!" println从第一个线程开始,第二个线程确实会挂起.这种情况发生在MacOS和Linux上.
知道为什么吗?