1.

Compare sleep() and wait() methods in Java

Answer»

The execution of a thread can be paused in a multithreading environment in Java using the sleep() or wait() methods. The thread is paused for the required time using sleep() while the thread goes into a wait state using wait() and can only be revived by calling NOTIFY() or NOTIFYALL().

Some of the differences between sleep() and wait() are given as follows:

The sleep() METHODThe wait() method
The sleep() method is always called on the thread that is currently executing.The wait() method is called on an object. The lock object must be synchronized with the current thread.
The sleep() method does not release the monitor or the lock.The wait() method RELEASES the monitor or the lock.
The sleep() method is used to pause the execution for a given amount of time.The wait() method can be used for inter thread communication.
The thread is woken up after the required time using sleep() or INTERRUPT() is called.The thread is woken up after the notify() or notifyAll() methods are called by the object.
The sleep() method can be used for multi thread synchronization.The wait() method can be used for time synchronization.

An example of sleep() is given as follows:

synchronized(LOCK) {      Thread.sleep(1000); }

An example of wait() is given as follows:

synchronized(LOCK) {      LOCK.wait(); }


Discussion

No Comment Found