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

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

DDD
Release: 2024-10-31 16:16:57
Original
921 people have browsed it

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

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

  • In the constructor, the main thread creates multiple threads and adds them to an ArrayList.
  • After printing "Runners ready," it calls notifyAll() to notify all threads.

Runner.java

  • In the run() method, each runner enters a wait() condition, waiting for a notification from the main thread.

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template