为什么在使用线程类对象作为锁时可以调用wait()方法而不调用notify()方法?

huangapple go评论62阅读模式
英文:

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实例上使用waitnotifynotifyAll

发生的情况如下:

  • 主方法创建了一个新的线程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 calls t1.notifyAll() as per the documentation
  • this wakes up the main thread

huangapple
  • 本文由 发表于 2023年4月11日 15:29:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75983423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定