小编Mar*_*rco的帖子

意外的线程唤醒

我期待以下示例中的第二个线程挂起,因为它等待没有相应通知的对象.相反,它落到了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上.

知道为什么吗?

java multithreading notify wait spurious-wakeup

4
推荐指数
1
解决办法
95
查看次数

标签 统计

java ×1

multithreading ×1

notify ×1

spurious-wakeup ×1

wait ×1