英文:
Why can the wait() method be called without the notify() method when using the thread class object as a lock?
问题
在上面的代码中,我没有调用任何notify或notifyAll方法,但主线程仍然醒来并正常执行。我想知道为什么。谢谢。
英文:
public class WaitMain {
public volatile static int i = 0;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(){
public void run(){
for (i = 0; i < 1000000; i++);
}
};
t1.start();
synchronized (t1){
t1.wait();
}
System.out.println(i);
}
}
In the above code, I didn't call any notify or notifyAll methods, but the main thread still woke up and executed normally. I want to know why. Thanks.
答案1
得分: 4
这是关于Thread.join()
的描述:
当线程终止时,将调用
this.notifyAll
方法。建议应用程序不要在Thread实例上使用wait
,notify
或notifyAll
。
发生的情况如下:
- 主方法创建了一个新的线程
t1
并启动它。 - 然后调用了
t1.wait()
。 - 一段时间后,线程
t1
终止,并根据文档隐式调用了t1.notifyAll()
。 - 这唤醒了主线程。
英文:
The description for this is a bit hidden in the documentation of Thread.join()
:
> As a thread terminates the this.notifyAll
method is invoked. It is recommended that applications not use wait
, notify
, or notifyAll
on Thread instances.
What happens is this:
- the main method creates a new Thread
t1
and starts it - it then calls
t1.wait()
- the Thread
t1
some time later terminates and implicitly callst1.notifyAll()
as per the documentation - this wakes up the main thread
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论