Home> Java> javaTutorial> body text

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

WBOY
Release: 2023-09-03 17:21:07
forward
679 people have browsed it

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

It is not possible tocall thewait()method without acquiring the lock. In Java, once the lock is acquired, we need to call thewait() method on the object (can be with or without timeout). If we try to call thewait()method without acquiring the lock, it may throw ajava.lang.IllegalMonitorStateExceptionexception.

Example

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

In the above example, we need to call thewait()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 thewait()method and declarerun()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
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!