Home > Java > javaTutorial > body text

Why am I getting an IllegalMonitorStateException when using wait() and notify() in Java?

Mary-Kate Olsen
Release: 2024-10-31 23:14:29
Original
475 people have browsed it

Why am I getting an IllegalMonitorStateException when using wait() and notify() in Java?

IllegalMonitorStateException in Java Wait and Notify

Understanding Wait and Notify

The wait() and notify() methods of the Object class are used for inter-thread communication in Java. wait() causes the calling thread to wait until another thread calls notify() on the same object, releasing the thread to continue execution.

IllegalMonitorStateException

The IllegalMonitorStateException is thrown when a thread attempts to wait on an object without holding its intrinsic lock. This lock is acquired by synchronizing on the object using synchronized blocks or methods.

In the Provided Code

The code you provided encounters this exception because the wait() method is called without synchronizing on the appropriate object. In the Runner class, the wait() method is called within the run() method. However, the run() method is not synchronized on any object.

Solution

To fix this, you must synchronize the run() method on the Main.main object, which is the object that wait() is called on. This ensures that the current thread holds the intrinsic lock on Main.main before attempting to wait.

<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 synchronization ensures that the current thread acquires the intrinsic lock on Main.main before calling wait(), preventing the IllegalMonitorStateException from being thrown.

The above is the detailed content of Why am I getting an IllegalMonitorStateException when using wait() and notify() 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!