Java Wait and Notify: Overcoming IllegalMonitorStateException
In your attempt to implement wait and notify in Java, you encountered the elusive IllegalMonitorStateException. This error indicates that the current thread does not own the monitor associated with the object being invoked upon.
Understanding Ownership in wait and notify
As stated in the Javadocs for wait(), a thread must own the monitor of an object before executing wait() on that object. Similarly, notify() and notifyAll() operations also require the invoking thread to own the monitor.
Applying Synchronization to the Runner Class
To resolve the IllegalMonitorStateException, you need to ensure that the current thread owns the monitor of the Main object before executing wait(). You can achieve this by synchronizing the run() method of the Runner class as follows:
<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>
By synchronizing on Main.main, you are ensuring that the current thread acquires the monitor of the Main object before executing wait(). This allows you to successfully wait for notification without encountering the IllegalMonitorStateException.
Note on Thread Ownership
In Java, a thread acquires ownership of an object's monitor when it executes synchronized blocks or synchronized methods of that object. It releases ownership when execution leaves the synchronized block or method.
The above is the detailed content of Why Am I Getting an IllegalMonitorStateException When Using Java\'s Wait and Notify?. For more information, please follow other related articles on the PHP Chinese website!