Difference between Thread.sleep() and Object.wait()

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.

6 Responses to Difference between Thread.sleep() and Object.wait()

  1. Neo says:

    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.

  2. Shrinivasan says:

    Nice post! was helpful.

  3. Hari says:

    It would be apt for readers to remind themselves of ‘join’ method also in this context.

  4. khalid says:

    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()……..

  5. Lokesh says:

    Nice Post….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 30 other followers