为什么这段代码会抛出IllegalMonitorStateException?

时间:2013-12-02 20:47:14

标签: java multithreading monitoring wait

请向我解释为什么我的代码会在等待函数中抛出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();
}

1 个答案:

答案 0 :(得分:6)

您只能在该对象的wait()内拨打synchronized

synchronized (targetW)内,您可以致电targetW.wait()