Java: Are all monitors released when thread waits on an object?

a 夏天 提交于 2019-11-30 11:11:00

Only b.

The authoritarian source for these type of questions is the Java Language Specification. The relevant section in this case is 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. [...]

From the Java API documentation of the Object class:

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

So, calling b.wait() releases the lock on b only.

AFAIK only b. It's a classic source of deadlocks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!