gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:40:05 25 4
gpt4 key购买 nike

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

最佳答案

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

synchronized(targetW)内,您可以调用targetW.wait()

关于java - 为什么这段代码会抛出 IllegalMonitorStateException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20337518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com