Java 中断线程时出现IllegalMonitorStateException
我得到了一个非法的监视器状态例外,我觉得我无法阅读更多,所以我问是否有人知道我做错了什么。当计数器(Gate类中线程之间的共享资源)陷入等待状态后,我在程序运行结束时收到此错误。为了告诉线程结束,我从main方法中断它们 在其他方法中,Counter类具有关键部分Java 中断线程时出现IllegalMonitorStateException,java,multithreading,wait,Java,Multithreading,Wait,我得到了一个非法的监视器状态例外,我觉得我无法阅读更多,所以我问是否有人知道我做错了什么。当计数器(Gate类中线程之间的共享资源)陷入等待状态后,我在程序运行结束时收到此错误。为了告诉线程结束,我从main方法中断它们 在其他方法中,Counter类具有关键部分 private int currentValue; /* to keep score of people passing */ /* critical section */ p
private int currentValue; /* to keep score of people passing */
/* critical section */
public synchronized boolean isFull() {
if(busy) { /* lock */
try {
wait();
} catch (InterruptedException e) {
System.out.println("isFull was interrupted waiting");
}
}
busy=true;
/* is not full notify threads waiting to resume work*/
if(currentValue < maxValue) {
notify();
busy=false; /* unlock */
return false;
}
/* do not notify threads */
return true;
}
/* critical section */
public synchronized void addPersons() {
if(busy) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("addPersons was interrupted waiting");
}
}
busy=true;
currentValue += nr_p;
notify();
busy=false;
}
public synchronized int getValue() {
return currentValue;
}
主要方法有以下几行:
while(counter.getValue() < MAX) {
Thread.sleep(3000);
}
System.out.println("Announcement: Ship is full!");
/* wait for child threads to finish */
for(Gate g: gates) {
g.close(); /* interrupts thread in gate object */
System.out.println(g.getNoOfPassangers() + " passed through gate nr " + g.getId());
}
}
while(counter.getValue()
这让我抓狂,我已经读了所有关于监视器错误的内容 t.wait()代码>应位于同步(t)
块中
但是,我在您的代码中看不到任何t.notifyAll()
,因此看起来您可以永远等待。还要注意,标准习惯用法是在循环中等待以处理虚假唤醒。来自文档:抛出以指示线程试图在对象的监视器上等待,或通知其他线程在不拥有指定监视器的情况下在对象的监视器上等待。创建用于锁定的成员变量。打电话等一下。这有点帮助。看到了吗
while(counter.getValue() < MAX) {
Thread.sleep(3000);
}
System.out.println("Announcement: Ship is full!");
/* wait for child threads to finish */
for(Gate g: gates) {
g.close(); /* interrupts thread in gate object */
System.out.println(g.getNoOfPassangers() + " passed through gate nr " + g.getId());
}
}