我得到一个 IllegalMonitorStateException 并且我觉得我无法阅读更多内容,所以我问是否有人知道我做错了什么。我在程序运行结束时收到此错误,在计数器(门类中的线程之间的共享资源)处于等待状态之后。为了告诉线程结束,我从 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());
}
}
这让我发疯,我已经阅读了有关监视器错误的所有信息。