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?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With