JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Difference between sleep and wait in java

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.

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.

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

.