Java's Wait and Notify: Understanding IllegalMonitorStateException
In Java, wait and notify methods allow threads to synchronize their execution. However, using these methods incorrectly can lead to IllegalMonitorStateException.
To understand why, let's analyze the provided code:
Main.java
Runner.java
The issue lies in the wait() call in Runner.run(). When a thread calls wait() on an object, it must own that object's monitor. Ownership is established by synchronizing on the object.
To fix the issue, synchronize on Main.main within the wait() call:
<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 ensures that the current thread owns Main.main's monitor before entering the wait() condition.
The same principle applies to notify() and notifyAll(). A thread must own the object's monitor before issuing these methods.
The above is the detailed content of Why Am I Getting IllegalMonitorStateException When Using Java\'s Wait and Notify?. For more information, please follow other related articles on the PHP Chinese website!