Home >Java >javaTutorial >In Java, can we call wait() method without acquiring the lock?

In Java, can we call wait() method without acquiring the lock?

WBOY
WBOYforward
2023-09-03 17:21:07790browse

In Java, can we call wait() method without acquiring the lock?

It is not possible to call the wait() method without acquiring the lock. In Java, once the lock is acquired, we need to call the wait() method on the object (can be with or without timeout). If we try to call the wait() method without acquiring the lock, it may throw a java.lang.IllegalMonitorStateException exception.

Example

public class ThreadStateTest extends Thread {
   public void run() {
      try {
<strong>         </strong>wait(1000);
      } catch(InterruptedException ie) {
         ie.printStackTrace();
      }
   }
   public static void main(String[] s) {
      ThreadStateTest test = new ThreadStateTest();
<strong>      </strong>test.start();
   }
}

In the above example, we need to call the wait() method without acquiring the lock, so that a ## will be generated at runtime. #IllegalMonitorStateException . In order to solve this problem, we need to acquire the lock before calling the wait() method and declare run() methodsynchronized.

Output

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at ThreadStateTest.run(ThreadStateTest.java:4)

The above is the detailed content of In Java, can we call wait() method without acquiring the lock?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete