我得到一个IllegalMonitorStateException,我觉得我不能读更多,所以我问是否有人知道我做错了什么。我在程序运行结束时,在计数器(Gate类中的线程之间的共享资源)卡在等待之后得到此错误。告诉线程结束我从main方法中断它们。
Counter类有其他几个关键部分的方法。
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;
}
类Gate中的run方法(也有线程):
public void run() {
while(!blocked) {
int waitTime = (r.nextInt(5) + 1) * 1000; /* random seconds */
if(counter.isFull(gatenr))
try {
t.wait(); /* here is where the IllegalMonitorStateException occurs. */
} catch (InterruptedException e) {
System.out.println("Shutting gate off from waiting");
}
if(t.isInterrupted()) { /* check if thread is interrupted */
System.out.println("breaking");
break;
}
counter.addPersons(1);
nrOfPassengers++;
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
System.out.println("Shutting gate off from sleep");
}
}
}
/* used by main to interrupt threads from wait statement and close gate */
public synchronized void close() {
t.interrupt();
blocked = true;
}
主要方法有以下几行:
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());
}
}
这让我发疯,我已经阅读了有关显示器错误的所有信息。
答案 0 :(得分:1)
t.wait();
应该在synchronized(t)
块中。
但是我在代码中看不到任何t.notifyAll()
,所以看起来你可以永远等待。另请注意,标准习惯是在循环中等待机智虚假唤醒。