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.
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(); } }
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.
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!