非法监视器状态异常

发布于 2024-08-17 23:59:59 字数 210 浏览 7 评论 0原文

是什么导致我在这段代码中得到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

無處可尋 2024-08-24 23:59:59

Integer 类型或类似类型? -- 将不可变的 Integer 对象替换为另一个对象。因此,您在与 synchronized 不同的对象上调用 notify

您的代码相当于:

Integer syncConunt = Integer.valueOf(5);
[...]
synchronized (syncCount) {
    syncCount = Integer.valueOf(syncCount.intValue() + 1);
    syncCount.notify();
}

您并不孤单。甚至在 J2SE 5.0 之前,我就已经在一本书中看到了在同步块中分配引用的示例代码。一般来说,将锁定字段标记为 final 是个好主意。

另一个重要的一点是代码在它不“拥有”的对象上同步。 Integer 对象是共享的(如果使用 -128 到 127 甚至更远的值调用,Integer.valueOf(int) 将返回完全相同的实例)。如果这是由两段不相关的代码完成的,那么就会存在隐藏的交互。这适用于在不相关代码之间共享实例的任何类型。常见的例子有IntegerStringClass(由静态同步方法使用)和Thread(在Sun的实现中, Thread恰好被用作join的锁)。

Of type Integer or similar? -- replaces the immutable Integer object with another one. Therefore you are calling notify on a different object than the synchronized.

Your code is the equivalent of:

Integer syncConunt = Integer.valueOf(5);
[...]
synchronized (syncCount) {
    syncCount = Integer.valueOf(syncCount.intValue() + 1);
    syncCount.notify();
}

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 are Integer, String, Class (used by static synchronised methods) and Thread (in Sun's implementation, Thread happens to be used as a lock for join).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文