请向我解释为什么我的代码会在等待函数中抛出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();
}
答案 0 :(得分:6)
您只能在该对象的wait()
块内拨打synchronized
。
在synchronized (targetW)
内,您可以致电targetW.wait()
。