请向我解释为什么我的代码会在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();
}
最佳答案
您只能在该对象的wait()
块内调用synchronized
。
在synchronized (targetW)
内部,您可以调用targetW.wait()
。