Home  >  Article  >  Java  >  Why Am I Getting an IllegalMonitorStateException When Using Java\'s Wait and Notify?

Why Am I Getting an IllegalMonitorStateException When Using Java\'s Wait and Notify?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 19:39:03731browse

Why Am I Getting an IllegalMonitorStateException When Using Java's Wait and Notify?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn