Understanding Wait and Notify
The wait() and notify() methods of the Object class are used for inter-thread communication in Java. wait() causes the calling thread to wait until another thread calls notify() on the same object, releasing the thread to continue execution.
IllegalMonitorStateException
The IllegalMonitorStateException is thrown when a thread attempts to wait on an object without holding its intrinsic lock. This lock is acquired by synchronizing on the object using synchronized blocks or methods.
In the Provided Code
The code you provided encounters this exception because the wait() method is called without synchronizing on the appropriate object. In the Runner class, the wait() method is called within the run() method. However, the run() method is not synchronized on any object.
Solution
To fix this, you must synchronize the run() method on the Main.main object, which is the object that wait() is called on. This ensures that the current thread holds the intrinsic lock on Main.main before attempting to wait.
<code class="java">class Runner implements Runnable { public void run() { try { synchronized (Main.main) { Main.main.wait(); } } catch (InterruptedException e) {} System.out.println("Runner away!"); } }</code>
This synchronization ensures that the current thread acquires the intrinsic lock on Main.main before calling wait(), preventing the IllegalMonitorStateException from being thrown.
The above is the detailed content of Why am I getting an IllegalMonitorStateException when using wait() and notify() in Java?. For more information, please follow other related articles on the PHP Chinese website!