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
Release: 2023-09-03 17:21:07
forward
784 people have browsed it

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();
   }
}
Copy after login

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

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!

Related labels:
source:tutorialspoint.com
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