gpt4 book ai didi

Java:线程等待对象时是否释放所有监视器?

转载 作者:太空狗 更新时间:2023-10-29 22:32:41 31 4
gpt4 key购买 nike

在一个线程可以等待一个对象之前,它必须获得该对象的监视器。然后释放监视器,线程一旦醒来就尝试重新获取它。

但是当线程调用 wait 时,其他监视器会发生什么情况?

考虑这个例子:

   Object a = // ...   Object b = // ...   synchronized(a)   {       synchronized(b)       {           b.wait();           // continue       }   }

当线程调用b.wait()时,是否会释放ab上的锁>,还是只有 b

最佳答案

只有 b

此类问题的专制来源是 Java 语言规范。本例中的相关部分是 17.8 Wait Sets and Notification :

Let thread t be the thread executing the wait method on object m, and let n be the number of lock actions by t on m that have not been matched by unlock actions. One of the following actions occurs.

  • [...]
  • Otherwise, the following sequence occurs:

    1. Thread t is added to the wait set of object m, and performs n unlock actions on m.
    2. [...]

关于Java:线程等待对象时是否释放所有监视器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6265330/

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