【问题标题】:why does this code throw a IllegalMonitorStateException?为什么这段代码会抛出 IllegalMonitorStateException?
【发布时间】:2013-12-02 20:47:13
【问题描述】:

请向我解释为什么我的代码会在等待函数中抛出 IllegalMonitorStateException,据我所知,只有在未在同步部分完成时才会发生这种情况?

private void deliver(int target) {
    Warehouse targetW = targets[target];
    targetW.deliver();
    System.out.println(name + " starts to deliver too " +
                       targetW.getName());
    int sleepTime = DELIVERY_TIME / LOADING_CAPACITY;
    int counter = 0;
    while (counter < LOADING_CAPACITY) {
        synchronized (targetW) {
            while (!targetW.fill(1)) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        counter++;
        try {
            sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    leaveMSG(targetW);
    targetW.delivered();
}

【问题讨论】:

  • 这可能是每个具有内在锁的对象的缺点之一。这样的错误不会被捕获。我仍然说应该有一个名为“Lock”的特定类用于所有锁
  • 对我来说听起来像是信号量。我也在使用它们,但在这种情况下,由于超出了使用此功能的原因,使用起来更加复杂。
  • @Gray 这看起来不像是重复的。操作:as far as I know this only happens if its not done in a synchronized part。他知道这一点。他的问题更具体一点,因为他忘了指定对象。然而,它的答案对此很有帮助,但问题本身并不是重复的。
  • 问题是一样的,但这个答案要好得多:stackoverflow.com/a/1537400/179850

标签: java multithreading monitoring wait


【解决方案1】:

您只能在该对象上的synchronized 块内调用wait()

synchronized (targetW)内,可以拨打targetW.wait()

【讨论】:

  • 啊哦,是的,上个月使用信号量并再次忘记了那个细节^^ thx
  • @user3038456 +1 这同样适用于我假设你在某个地方的 notify/notifyAll。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-18
相关资源
最近更新 更多