Reputation: 1132
I have already searched this error in here, but I think that my piece of code looks correct:
This is an excerpt of the code, if I tried to run the code I get a java.lang.IllegalMonitorStateException: current thread is not owner. The error is in the cond.wait() method.
public void takeARest() {
lock.lock();
try {
while (disembark < totalPassengers) {
System.err.printf("Held by %s%n",lock.isHeldByCurrentThread());
cond.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
Any ideas?
Upvotes: 4
Views: 1558
Reputation: 5558
For that you want Condition.await()
.
Object.wait()
is a different method that requires to hold the monitor of the object (synchornized(cond){}
around the call)
So:
public void takeARest() {
lock.lock();
try {
while (disembark < totalPassengers) {
System.err.printf("Held by %s%n",lock.isHeldByCurrentThread());
cond.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
Upvotes: 5