Home > Java > javaTutorial > Why Do I Get `IllegalMonitorStateException` When Using `wait()` in Java?

Why Do I Get `IllegalMonitorStateException` When Using `wait()` in Java?

Mary-Kate Olsen
Release: 2024-11-01 05:25:02
Original
657 people have browsed it

Why Do I Get `IllegalMonitorStateException` When Using `wait()` in Java?

Java Wait and Notify: Understanding IllegalMonitorStateException

In multithreaded programming, wait() and notify() methods allow threads to coordinate their actions. However, using these methods incorrectly can lead to IllegalMonitorStateException.

In the given code snippet, within class Main, you attempt to call wait() on Main.main. However, you encounter an IllegalMonitorStateException. This is because the current thread (main thread) does not hold the lock on the Main.main object.

To address this issue, you need to synchronize the code block where wait() is called. This can be achieved by using a synchronized(...) block on the object that you want to wait on. In this case, it's the Main.main object:

<code class="java">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 the Main.main object, you ensure that the current thread (the runner thread) acquires the lock on the object before executing the wait(). When the notifyAll() is called from the Main class, all the runner threads will be notified and can proceed with their execution.

The same principle applies to notify() and notifyAll() methods. They can only be called by the thread that holds the lock on the synchronized object.

The above is the detailed content of Why Do I Get `IllegalMonitorStateException` When Using `wait()` in Java?. 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