Java:当线程等待对象时,是否释放所有监视器?
在线程可以等待
对象之前,它必须获取该对象的监视器。然后释放监视器,并且线程在唤醒后尝试重新获取它。
但是,当线程调用 wait
时,该线程持有的其他监视器会发生什么情况?
考虑这个例子:
Object a = // ... Object b = // ... synchronized(a) { synchronized(b) { b.wait(); // continue } }
当线程调用b.wait()
时,它会释放a
和b两者上的锁吗? code>,还是只有
b
?
Before a thread can wait
on an object, it has to acquire a monitor on that object. The monitor is then released, and the thread attempts to re-acquired it once it awakes.
But what happens to other monitors the thread holds when it calls wait
?
Consider this example:
Object a = // ... Object b = // ... synchronized(a) { synchronized(b) { b.wait(); // continue } }
When the thread calls b.wait()
, will it release the locks on both a
and b
, or only b
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只有
b
。此类问题的权威来源是 Java 语言规范。本例中的相关部分是 17.8 等待集和通知< /a>:
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:
来自对象类:
因此,调用
b.wait()
仅释放b
上的锁。From the Java API documentation of the Object class:
So, calling
b.wait()
releases the lock onb
only.仅据我所知 b.这是僵局的典型根源。
AFAIK only b. It's a classic source of deadlocks.