One of the common interview question is “What is difference between sleep and wait in java”.Before we actually see differences,let me give you brief introduction of both.
sleep
- It causes current executing thread to sleep for specific amount of time.
- Its accuracy depends on system timers and schedulers.
- It keeps the
monitors
it has acquired, so if it is called from synchronized context, no other thread can enter that block or method. - If we call
interrupt()
method , it will wake up the sleeping thread.
1 2 3 4 5 6 7 8 |
synchronized(lockedObject) { Thread.sleep(1000); // It does not release the lock on lockedObject. // So either after 1000 miliseconds, current thread will wake up, or after we call //t. interrupt() method. } |
wait
- It causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object
- It must be called from
synchronized
context i.e. from block or method.It means before wait() method is called,current thread must have lock on that object. - It releases lock on the object on which it is called and added to wait list, so another thread can acquire lock on the object.
1 2 3 4 5 6 7 8 |
synchronized(lockedObject) { lockedObject.wait(); // It releases the lock on lockedObject. // So until we call notify() or notifyAll() from other thread,It will // not wake up } |
sleep vs wait:
Parameter
|
wait
|
sleep
|
Synchonized
|
wait should be called from synchronized context i.e. from block or method, If you do not call it using synchronized context, it will throw IllegalMonitorStateException |
It need not be called from synchronized block or methods
|
Calls on
|
wait method operates on Object and defined in Object class |
Sleep method operates on current thread and is in java.lang.Thread
|
Release of lock
|
wait release lock of object on which it is called and also other locks if it holds any
|
Sleep method does not release lock at all
|
Wake up condition
|
until call notify() or notifyAll() from Object class
|
Until time expires or calls interrupt()
|
static
|
wait is non static method
|
sleep is static method
|
You can go through core java interview questions for beginners and experienced for more such questions.