How to use wait and notify in Java without IllegalMonitorStateException?
To be able to call notify() you need to synchronize on the same object.
synchronized (someObject) {
someObject.wait();
}
/* different thread / object */
synchronized (someObject) {
someObject.notify();
}
While using the wait
and notify
or notifyAll
methods in Java the following things must be remembered:
- Use
notifyAll
instead ofnotify
if you expect that more than one thread will be waiting for a lock. - The
wait
andnotify
methods must be called in a synchronized context. See the link for a more detailed explanation. - Always call the
wait()
method in a loop because if multiple threads are waiting for a lock and one of them got the lock and reset the condition, then the other threads need to check the condition after they wake up to see whether they need to wait again or can start processing. - Use the same object for calling
wait()
andnotify()
method; every object has its own lock so callingwait()
on object A andnotify()
on object B will not make any sense.