Difference between Thread.sleep() and Object.wait()
December 20, 2008 6 Comments
One of my favorite interview question is: What is the difference between sleep() and wait() method? The only commonality between these two method is both halts the current thread execution. The purpose and usage are entirely different.
Object.wait() method:
a) This method available in Object.class
b) It can be used only inside the synchronized method or block.
c) It halts the current thread execution and releases the lock of the object. Hence other thread can use the object for execution.
d) Wait state can be terminated by calling Object.notify() method.
e) Wait() and notify() methods are specific to an instance of an object. (Not at the class level)
Thread.sleep() method:
a) This method available in Thread.class.
b) It can be used anywhere in the code to halt the current thread execution for the specified time.
c) The sleep state can be terminated by invoking interrupt() method of the thread instance.
Thread.sleep() is most frequently used method. Object.wait() is used in concurrent thread access codes only.
Adding to your post:
Object.wait() method:
f) The wait state can be terminated by invoking interrupt() method of the thread instance waiting on the Object Monitor.
Using sleep makes your codes non-scalable across hardwares, where a nicely written wait/notify code scales well.
Nice post! was helpful.
It would be apt for readers to remind themselves of ‘join’ method also in this context.
Good Post
plz explain about notify() method,
according to yu if u call
wait() method then lock of object will be release
then why u use notify()……..
Nice Post….