gpt4 book ai didi

java - 为什么线程对象的wait方法不需要notify方法来唤醒?

转载 作者:行者123 更新时间:2023-12-01 16:43:53 24 4
gpt4 key购买 nike

当我在线程对象上调用 wait() 方法时,等待线程将在同步线程完成运行时被唤醒,为什么线程对象的行为与使用 wait() 的普通对象不同?

Thread thread1 = new Thread(()-> {
System.out.println("thread 1 start");
try {
Thread.sleep(3000);
System.out.println("thread over");
} catch (InterruptedException e) {
e.printStackTrace();
}});
thread1.start();

synchronized (thread1) {
try {
thread1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

System.out.println("main thread wake up");

我预计主线程在 3 秒后不会唤醒,但事实并非如此。

最佳答案

The javadoc说:

As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

关于java - 为什么线程对象的wait方法不需要notify方法来唤醒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56686069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com