I\'m new to using wait() and notify() in Java and I\'m getting an IllegalMonitorStateException.
Main Code
public class ThreadTest
This
private static Integer state = 0;
is equivalent to
private static Integer state = Integer.valueOf(0);
The invocation of valueOf(0)
returns a reference to an Integer
object, call it A.
You then do
synchronized(state) {
your thread acquires the lock on the object referenced by state
, currently that is A.
You then do
state = 1;
which is equivalent to
state = Integer.valueOf(1);
which gives you a different reference to an Integer
object, call it B, and assigns it to state
. When you then call
state.notify();
you're invoking notify()
on an object, B, for which your thread doesn't own the monitor. You can't call notify
or wait
on objects for which your thread doesn't own the monitor.