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.
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.
OutputException 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!