Java Object wait
When we call the wait method which eventually stops the execution of a current thread and gives away the object lock to the other thread of the respective class. Means whatever the lock acquired by a thread will be released to other threads.
wait is one of the method in java.lang.Object class, which is having three signatures as follows
- wait()
- wait(long timeout)
- wait(long timeout, int nanos)
wait method can be called only in synchronized blocks or methods only.
If wait method without arguments invokes or calls, Then current thread will be releasing a lock on the Object of a particular class and stops the execution of further proceeding. The execution of a thread stops until the notify() or notifyAll() method is invoked on that particular object. As mentioned earlier, wait method can only be called in synchronized block otherwise it will leads to java.lang.IllegalMonitorStateException
Object wait method example
public class Wait { public static void main(String[] args) throws InterruptedException { new Wait().waitExample(); } public void waitExample() throws InterruptedException { synchronized (this) { this.wait(); System.out.println("This will never be printed"); } } }Output
Nothing gets printed...
If wait method with timeout invokes or calls, Then current thread will be releasing a lock on the Object of a particular class and stops the execution of further proceeding.This execution of a thread stops until the timeout is expired. The timeout units is a milliseconds.
wait example with timeout
public class Wait { public static void main(String[] args) throws InterruptedException { new Wait().waitExample(); } public void waitExample() throws InterruptedException { synchronized (this) { this.wait(100L); System.out.println("This will be printed after 100 millis"); } } }Output
This will be printed after 100 millis