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.

Advertisements

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

  6. cxcdfgrerf says:

    墨香外传服务端冒险岛服务端绝对女神服务端卧龙吟问仙服务端
    神将三国服务端仙境传说ro服务端天龙八部服务端传说45服务端
    完美世界服务端九阴真经服务端凡人修真2服务端天之炼狱服务端
    传奇广告代理(详细介绍)http://www.e7if.com/index15.htm
    IDC服务器以及空间租用-(详细介绍)http://www.e7if.com/
    传奇开sf一条龙开区服务官方网站http://www.e7if.com
    天龙八部开私服一条龙服务-www.e7if.com
    魔域私服开区一条龙服务-www.e7if.com-客服咨询QQ(扣扣)49333685
    后浪科技www.e7if.com商业版本免费开放下载(只能单线程单个下载)
    http://www.e7if.com/soft/index.html

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: