Home > Java > javaTutorial > body text

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

Barbara Streisand
Release: 2024-10-30 19:39:03
Original
747 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!