非法监视器状态异常
是什么导致我在这段代码中得到 IllegalMonitorStateException
synchronized(syncCount){
syncCount--;
syncCount.notify();
}
我有点困惑,因为据我所知,运行线程必须监视调用通知的对象。在我看来,我的代码不可能是错误的,但不知何故它是错误的。
What can cause that i get IllegalMonitorStateException in this code
synchronized(syncCount){
syncCount--;
syncCount.notify();
}
I'm little confused, since, as far as I know running thread must have monitor on object who's notify is called. It looks to me that my code can not be wrong, but somehow it is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Integer
类型或类似类型?--
将不可变的Integer
对象替换为另一个对象。因此,您在与synchronized
不同的对象上调用notify
。您的代码相当于:
您并不孤单。甚至在 J2SE 5.0 之前,我就已经在一本书中看到了在同步块中分配引用的示例代码。一般来说,将锁定字段标记为
final
是个好主意。另一个重要的一点是代码在它不“拥有”的对象上同步。
Integer
对象是共享的(如果使用 -128 到 127 甚至更远的值调用,Integer.valueOf(int)
将返回完全相同的实例)。如果这是由两段不相关的代码完成的,那么就会存在隐藏的交互。这适用于在不相关代码之间共享实例的任何类型。常见的例子有Integer
、String
、Class
(由静态同步方法使用)和Thread
(在Sun的实现中,Thread
恰好被用作join
的锁)。Of type
Integer
or similar?--
replaces the immutableInteger
object with another one. Therefore you are callingnotify
on a different object than thesynchronized
.Your code is the equivalent of:
You are not alone. Even before J2SE 5.0, I have seen example code published in a book that assigned a reference within a synchronized block. In general it is a good idea to mark lock fields
final
.Another significant point is that the code synchronising on an object that it does not "own".
Integer
objects are shared (Integer.valueOf(int)
will return exactly the same instance if called with values between -128 and 127, and perhaps further). If this were done by two pieces of unrelated code, then there would hidden interactions. This applies to any type where instances are shared between unrelated code. Common examples areInteger
,String
,Class
(used by static synchronised methods) andThread
(in Sun's implementation,Thread
happens to be used as a lock forjoin
).