1360

What is the difference between await() andsleep() in Threads?

Is my understanding that await()-ing Thread is still in running mode and uses CPU cycles but asleep()-ing does not consume any CPU cycles correct?

Why do we havebothwait() andsleep()?

How does their implementation vary at a lower level?

Ola Ström's user avatar
Ola Ström
5,4796 gold badges31 silver badges51 bronze badges
askedJun 24, 2009 at 6:48
Geek's user avatar
7
  • 64
    very good question. semantics of both are easy to confuse.CommentedJun 24, 2009 at 7:25
  • 1
    Very nice questions but they are 2 in one. Why do we have both is not the same as how they can (and not are!) implemented at a lower level. I've answered to that too.CommentedApr 19, 2012 at 10:39
  • Suppose a thread A is in a synchronized block , and while it is in the cpu from this thread is taken and given to another thread B. now in which state Thread A will go , will the other threads waiting on this synchronized block come inside now ?CommentedAug 17, 2013 at 8:22
  • 3
    Here's a good article describing it:qat.com/using-waitnotify-instead-thread-sleep-javaCommentedSep 27, 2013 at 13:59
  • 3
    its EXCATLY the opposite - sleep "uses" all of its available CPU-cycles but since the thread will be in "WAITING"-state these can be yielded if necessary - in fact most operating systems automatically yield the cyclesIF it is possible, hence your thread will not create any actual CPU-load ... it will do so on older operating systems, though. Object.wait(), on the other handNEVER uses any cycles (while being unnotified) because thats realized via software-interrupts in many cases - private, transient & transparent locks, implemented by the JVM. Thread.sleep is bad practise.CommentedDec 1, 2014 at 11:16

33 Answers33

920

Await can be "woken up" by another thread callingnotify on the monitor which is being waited on whereas asleep cannot. Also await (andnotify) must happen in a blocksynchronized on the monitor object whereassleep does not:

Object mon = ...;synchronized (mon) {    mon.wait();}

At this point the currently executing thread waitsand releases the monitor. Another thread may do

synchronized (mon) { mon.notify(); }

(on the samemon object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.

You can also callnotifyAll if more than one thread is waiting on the monitor – this will wakeall of them up. However, only one of the threads will be able to grab the monitor (remember that thewait is in asynchronized block) and carry on – the others will then be blocked until they can acquire the monitor's lock.

Another point is that you callwait onObject itself (i.e. you wait on an object's monitor) whereas you callsleep onThread.

Yet another point is that you can getspurious wakeups fromwait (i.e. the thread which is waiting resumes for no apparent reason). You shouldalwayswait whilst spinning on some condition as follows:

synchronized {    while (!condition) { mon.wait(); }}
MultiplyByZer0's user avatar
MultiplyByZer0
7,2693 gold badges35 silver badges49 bronze badges
answeredJun 24, 2009 at 6:50
oxbow_lakes's user avatar
Sign up to request clarification or add additional context in comments.

15 Comments

No, it cannot. It can only be interrupted.
When you are interrupting, you must know which thread you want to interrupt. When you're calling notify, you just need object, and you don't care if there is any other thread which 'waits' on this object. wait/notify is used for communication, while sleep is used for, ehm, sleeping.
@Geek - why in the world do you say wait() wastes CPU cycles?
Interruption is intended as a mechanism to gently encourage a thread to stop running entirely and cancel remaining operations.wait/notify are typically used to wait for some other thread to accomplish a task, or to wait until a certain condition is satisfied.
I read through all of the answers however I still feel a bit of missing information. Many people wrote down the definitions from the Javadoc and also the meaning of the two english words but I do not see Why I should ever use sleep instead of wait? What is the benchmarking and speed difference between the two? If I can do everything that I can do with sleep why should I ever choose sleep?
|
367

One key difference not yet mentioned is that:

  • sleep() doesnot release the lock it holds on the Thread,

    synchronized(LOCK) {    Thread.sleep(1000); // LOCK is held}
  • wait()releases the lock it holds on the object.

     synchronized(LOCK) {     LOCK.wait(); // LOCK is not held }
Ola Ström's user avatar
Ola Ström
5,4796 gold badges31 silver badges51 bronze badges
answeredJun 24, 2009 at 7:06
Robert Munteanu's user avatar

12 Comments

Waiting only releases the lock for the object youcall wait() on. It doesn't release anyother locks.
You don't actually need to call sleep from within a lock - locks and wait/notify go hand in hand but locks and sleep are unrelated.
@oxbow_lakes - I'd say that you should not sleep with locks, there are few uses cases for that. Just wanted to point out the differences.
@RobertMunteanu, Your answer misleadingly claims thatsleep holdsjava locks, but it doesn't. To have a fair comparison, we would comparesynchronized(OUTER_LOCK){ Thread.sleep(1000); } withsynchronized(OUTER_LOCK){ synchronized(LOCK){LOCK.wait();} } and we can see that both instructions don't release theOUTER_LOCK. If there's any difference, we can say thatsleep doesn't explicitlyusejava locks, but the question is asking about quote "how does their implementation vary at a lower level?" unquote.
@Pacerierwait() is associated with the condition of the inner most lock it's called from, in your code example,wait() can only releaseLOCK and notOUTER_LOCK. That's how Java monitor is designed anyway. A fair comparison would besynchronized(OUTER_LOCK){ synchronized(LOCK) { Thread.sleep(1000); } } andsynchronized(OUTER_LOCK){ synchronized(LOCK) { LOCK.wait(); } }. In this casesleep() will hold both locks whilewait() will releaseLOCK but still holdOUTER_LOCK
|
272

I foundthis post helpful. It puts the difference betweenThread.sleep(),Thread.yield(), andObject.wait() in human terms. To quote:

It all eventually makes its way down to the OS’s scheduler, which hands out timeslices to processes and threads.

sleep(n) says“I’m done with my timeslice, and please don’t give me another one for at least n milliseconds.” The OS doesn’t even try to schedule the sleeping thread until requested time has passed.

yield() says“I’m done with my timeslice, but I still have work to do.” The OS is free to immediately give the thread another timeslice, or to give some other thread or process the CPU the yielding thread just gave up.

wait() says“I’m done with my timeslice. Don’t give me another timeslice until someone calls notify().” As withsleep(), the OS won’t even try to schedule your task unless someone callsnotify() (or one of a few other wakeup scenarios occurs).

Threads also lose the remainder of their timeslice when they perform blocking IO and under a few other circumstances. If a thread works through the entire timeslice, the OS forcibly takes control roughly as ifyield() had been called, so that other processes can run.

You rarely needyield(), but if you have a compute-heavy app with logical task boundaries, inserting ayield()might improve system responsiveness (at the expense of time — context switches, even just to the OS and back, aren’t free). Measure and test against goals you care about, as always.

MultiplyByZer0's user avatar
MultiplyByZer0
7,2693 gold badges35 silver badges49 bronze badges
answeredAug 5, 2011 at 19:32
E-rich's user avatar

4 Comments

Yield is basically platform-dependent...javamex.com/tutorials/threads/yield.shtml
the explanation ofsleep(n) is implicitly saying that the currently running thread relinquishes the lock's monitor voluntarily, which isnot true. Quote fromThread's javadoc:"The thread does not lose ownership of any monitors."
@Jonathan there is no mentioning of monitors in the answer, and that is becausesleep does not have any special behaviour regarding monitor than any other Java method call, that is, it does not interact or modify them in any way. If you would say something about monitors you should specify thatwait will, in addition to the things said above, relinquish temporarily the lock on the object it is called on.
@Erich, Usewait(n) to compare withsleep(n). There's no sense in comparing using the no-arg one.
74

There are a lot of answers here but I couldn't find the semantic distinction mentioned on any.

It's not about the thread itself; both methods are required as they support very different use-cases.

sleep() sends the Thread to sleep as it was before, it just packs the context and stops executing for a predefined time. So in order to wake it up before the due time, you need to know the Thread reference. This is not a common situation in a multi-threaded environment. It's mostly used for time-synchronization (e.g. wake in exactly 3.5 seconds) and/or hard-coded fairness (just sleep for a while and let others threads work).

wait(), on the contrary, is a thread (or message) synchronization mechanism that allows you to notify a Thread of which you have no stored reference (nor care). You can think of it as a publish-subscribe pattern (wait == subscribe andnotify() == publish). Basically using notify() you are sending a message (that might even not be received at all and normally you don't care).

To sum up, you normally usesleep() for time-syncronization andwait() for multi-thread-synchronization.

They could be implemented in the same manner in the underlying OS, or not at all (as previous versions of Java had no real multithreading; probably some small VMs doesn't do that either). Don't forget Java runs on a VM, so your code will be transformed in something different according to the VM/OS/HW it runs on.

answeredApr 19, 2012 at 10:38
estani's user avatar

Comments

66

Here, I have listed few important differences betweenwait() andsleep() methods.
PS:Also click on the links to see library code (internal working, just play around a bit for better understanding).

wait()

  1. wait() method releases the lock.
  2. wait() is the method ofObject class.
  3. wait() is the non-static method -public final void wait() throws InterruptedException { //...}
  4. wait() should be notified bynotify() ornotifyAll() methods.
  5. wait() method needs to be called from a loop in order to deal with false alarm.

  6. wait() method must be called from synchronized context (i.e. synchronized method or block), otherwise it will throwIllegalMonitorStateException

sleep()

  1. sleep() method doesn't release the lock.
  2. sleep() is the method ofjava.lang.Thread class.
  3. sleep() is the static method -public static void sleep(long millis, int nanos) throws InterruptedException { //... }
  4. after the specified amount of time,sleep() is completed.
  5. sleep() better not to call from loop(i.e.see code below).
  6. sleep() may be called from anywhere. there is no specific requirement.

Ref:Difference between Wait and Sleep

Code snippet for calling wait and sleep method

synchronized(monitor){    while(condition == true){         monitor.wait()  //releases monitor lock    }    Thread.sleep(100); //puts current thread on Sleep    }

thread transition to different thread states

answeredDec 28, 2015 at 6:18
roottraveller's user avatar

6 Comments

Is it correct that a sleeping thread can be woken by calls to notify()? Some of the other posts here seem to imply a sleeping thread cannot be woken but interrupted.
Yes,Thread.sleep() is use for making processor time available to the other threads. the sleep period can be terminated by interrupts(i.e by JVM). Read thisstackoverflow.com/questions/4264355/…
That post also says interrupt() is what wakes a sleeping thread? I was referring to the thread state diagram you posted where it says notify or notifyAll bring a sleeping (not waiting) thread back to ready to run. I just want to make sure I understand that.
@berimbolonotify() ornotifyAll() areObject class methods. hence they are available will obj of all class(i.e. here withThread class too). see the codegrepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/…
OK I need to read more on thread scheduling as I cannot find examples of notify() or notifyAll() waking sleeping threads only interrupt() doing this. All examples relate notify() and notifyAll() to threads waiting on some monitor object.
|
48

Difference between wait() and sleep()

  • The fundamental difference is thatwait() is non static method ofObject andsleep() is a static method ofThread.
  • The major difference is thatwait() releases the lock whilesleep() doesn’t release any lock while waiting.
  • wait() is used for inter-thread communication whilesleep() is used to introduce a pause on execution, generally.
  • wait() should be called from inside synchronise or else we get anIllegalMonitorStateException, whilesleep() can be called anywhere.
  • To start a thread again fromwait(), you have to callnotify() ornotifyAll() indefinitely. As forsleep(), the thread gets started definitely after a specified time interval.

Similarities

  • Both make the current thread go into theNot Runnable state.
  • Both arenative methods.
answeredJul 24, 2015 at 6:48
Premraj's user avatar

Comments

29

There are some difference key notes i conclude after working on wait and sleep, first take a look on sample using wait() and sleep():

Example1: usingwait() andsleep():

synchronized(HandObject) {    while(isHandFree() == false) {        /* Hand is still busy on happy coding or something else, please wait */        HandObject.wait();    }}/* Get lock ^^, It is my turn, take a cup beer now */while (beerIsAvailable() == false) {    /* Beer is still coming, not available, Hand still hold glass to get beer,       don't release hand to perform other task */    Thread.sleep(5000);}/* Enjoy my beer now ^^ */drinkBeers();/* I have drink enough, now hand can continue with other task: continue coding */setHandFreeState(true);synchronized(HandObject) {    HandObject.notifyAll();}

Let clarity some key notes:

  1. Call on:
    • wait(): Call on current thread that hold HandObject Object
    • sleep(): Call on Thread execute task get beer (is class method so affect on current running thread)
  2. Synchronized:
    • wait(): when synchronized multi thread access same Object (HandObject) (When need communication between more than one thread (thread execute coding, thread execute get beer) access on same object HandObject )
    • sleep(): when waiting condition to continue execute (Waiting beer available)
  3. Hold lock:
    • wait(): release the lock for other object have chance to execute (HandObject is free, you can do other job)
    • sleep(): keep lock for at least t times (or until interrupt) (My job still not finish, i'm continue hold lock and waiting some condition to continue)
  4. Wake-up condition:
    • wait(): until call notify(), notifyAll() from object
    • sleep(): until at least time expire or call interrupt
  5. And the last point isuse when asestani indicate:

you normally use sleep() for time-syncronization and wait() for multi-thread-synchronization.

Please correct me if i'm wrong.

answeredMay 19, 2012 at 6:59
NguyenDat's user avatar

Comments

23

This is a very simple question, because both these methods have a totally different use.

The major difference is to wait to release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.

This was just a clear and basic explanation, if you want more than that then continue reading.

In case ofwait() method thread goes in waiting state and it won't come back automatically until we call thenotify() method (ornotifyAll() if you have more then one thread in waiting state and you want to wake all of those thread). And you need synchronized or object lock or class lock to access thewait() ornotify() ornotifyAll() methods. And one more thing, thewait() method is used for inter-thread communication because if a thread goes in waiting state you'll need another thread to wake that thread.

But in case ofsleep() this is a method which is used to hold the process for few seconds or the time you wanted. Because you don't need to provoke anynotify() ornotifyAll() method to get that thread back. Or you don't need any other thread to call back that thread. Like if you want something should happen after few seconds like in a game after user's turn you want the user to wait until the computer plays then you can mention thesleep() method.

And one more important difference which is asked often in interviews:sleep() belongs toThread class andwait() belongs toObject class.

These are all the differences betweensleep() andwait().

And there is a similarity between both methods: they both are checked statement so you need try catch or throws to access these methods.

I hope this will help you.

Charles Menguy's user avatar
Charles Menguy
41.6k18 gold badges97 silver badges117 bronze badges
answeredApr 19, 2012 at 7:02
Vikas Gupta's user avatar

Comments

17

source :http://www.jguru.com/faq/view.jsp?EID=47127

Thread.sleep() sends the current thread into the"Not Runnable" state for some amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread callst.interrupt() it will wake up the sleeping thread.

Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to callt.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone.

object.wait() sends the current thread into the"Not Runnable" state, likesleep(), but with a twist. Wait is called on an object, not a thread; we call this object the "lock object." Beforelock.wait() is called, the current thread must synchronize on the lock object;wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and calllock.notify(). This wakes up the original, waiting thread. Basically,wait()/notify() is likesleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.

Ravindra babu's user avatar
Ravindra babu
39.1k11 gold badges258 silver badges222 bronze badges
answeredNov 5, 2011 at 3:34
om singh's user avatar

Comments

16

Wait and sleep are two different things:

  • Insleep() the thread stops working for the specified duration.
  • Inwait() the thread stops working until the object being waited-on is notified, generally by other threads.
Zak's user avatar
Zak
7,0766 gold badges39 silver badges54 bronze badges
answeredJun 24, 2009 at 6:53
Itay Maman's user avatar

7 Comments

but you can interrupt a sleeping Thread. In that case wait() is redundant infact it wastes CPU cycles too :-(
Wait doesn't waste CPU cycles.
@Peter - I think it does. It waits() for its chunk of CPU cycles and then the OS gives the CPU cycles to other Threads. I think this might be OS dependant, I am not sure.
It would be very poor implementation of wait() if it wasted CPU cycles. wait/notify is used quite a lot for interthread communication.
@Pacerier the two constructs are intended for a different purpose. If you want a thread to stop for a fixed amount of time you usesleep, if you want it to stop until some input comes from the other you usewait/notify.interrupt is intended as a way to signal a thread that it should stop doing what it is doing and terminate. It is handled bysleep,wait but also blocking I/O functions (and you could implement functions with the same behaviour by calling the methodThread.interrupted()). As for the performance, functions are usually optimised for the goal they were designed.
|
15

sleep is a method ofThread,wait is a method ofObject, sowait/notify is a technique of synchronizing shared data in Java (usingmonitor), butsleep is a simple method of thread to pause itself.

answeredOct 30, 2012 at 22:46
pvllnspk's user avatar

Comments

10

sleep() is a method which is used to hold the process for few seconds or the time you wanted but in case of wait() method thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().

Themajor difference is thatwait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution, generally.

Thread.sleep() sends the current thread into the “Not Runnable” state for some amount of time. The thread keeps the monitors it has acquired — i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

object.wait() sends the current thread into the “Not Runnable” state, like sleep(), but with a twist. Wait is called on an object, not a thread; we call this object the “lock object.” Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the “wait list” associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.

synchronized(LOCK) {      Thread.sleep(1000); // LOCK is held}synchronized(LOCK) {      LOCK.wait(); // LOCK is not held}

Let categorize all above points :

Call on:

  • wait(): Call on an object; current thread must synchronize on the lock object.
  • sleep(): Call on a Thread; always currently executing thread.

Synchronized:

  • wait(): when synchronized multiple threads access same Object one by one.
  • sleep(): when synchronized multiple threads wait for sleep over of sleeping thread.

Hold lock:

  • wait(): release the lock for other objects to have chance to execute.
  • sleep(): keep lock for at least t times if timeout specified or somebody interrupt.

Wake-up condition:

  • wait(): until call notify(), notifyAll() from object
  • sleep(): until at least time expire or call interrupt().

Usage:

  • sleep(): for time-synchronization and;
  • wait(): for multi-thread-synchronization.

Ref:diffsleep andwait

answeredDec 23, 2013 at 6:07
Reegan Miranda's user avatar

Comments

7

In simple words, wait is wait Until some other thread invokes you whereas sleep is "dont execute next statement" for some specified period of time.

Moreover sleep is static method in Thread class and it operates on thread, whereas wait() is in Object class and called on an object.

Another point, when you call wait on some object, the thread involved synchronize the object and then waits. :)

answeredJun 24, 2009 at 6:51
Ratnesh Maurya's user avatar

2 Comments

Why do you need both ? Why sleep() is not sufficient ?
Notify is used for communication between threads. To call wait, you need some object, synchronize on it, and then call wait on it. To be notified, you need other thread to synchronize on thesame object, and call notify.
6

wait andsleep methods are very different:

  • sleep has no way of "waking-up",
  • whereaswait has a way of "waking-up" during the wait period, by another thread callingnotify ornotifyAll.

Come to think about it, the names are confusing in that respect; howeversleep is a standard name andwait is like theWaitForSingleObject orWaitForMultipleObjects in the Win API.

Ravindra babu's user avatar
Ravindra babu
39.1k11 gold badges258 silver badges222 bronze badges
answeredJun 24, 2009 at 6:52
Roee Adler's user avatar

2 Comments

But we can interrupt asleep couldn't we? so what's the difference with that sleep/interrupt vs wait/notify ?
You can interrupt a sleeping person, but you can only notify a waiting person. Threads are the same.
5

From this post :http://javaconceptoftheday.com/difference-between-wait-and-sleep-methods-in-java/

wait() Method.

1) The thread which calls wait() method releases the lock it holds.

2) The thread regains the lock after other threads call either notify() or notifyAll() methods on the same lock.

3) wait() method must be called within the synchronized block.

4) wait() method is always called on objects.

5) Waiting threads can be woken up by other threads by calling notify() or notifyAll() methods.

6) To call wait() method, thread must have object lock.

sleep() Method

1) The thread which calls sleep() method doesn’t release the lock it holds.

2) sleep() method can be called within or outside the synchronized block.

3) sleep() method is always called on threads.

4) Sleeping threads can not be woken up by other threads. If done so, thread will throw InterruptedException.

5) To call sleep() method, thread need not to have object lock.

answeredMar 19, 2015 at 6:46
user2485429's user avatar

Comments

4

Here wait() will be in the waiting state till it notify by another Thread but where as sleep() will be having some time..after that it will automatically transfer to the Ready state...

answeredSep 23, 2013 at 5:24
Rakhi Jaligama's user avatar

Comments

4
  1. wait() is a method ofObject class.
    sleep() is a method ofThread class.

  2. sleep() allows the thread to go tosleep state for x milliseconds.
    When a thread goes into sleep stateit doesn’t release the lock.

  3. wait() allows thread to release the lock andgoes to suspended state.
    This thread will be active when anotify() ornotifAll() method is called for the same object.

Ravindra babu's user avatar
Ravindra babu
39.1k11 gold badges258 silver badges222 bronze badges
answeredSep 9, 2014 at 10:52
Tnadev's user avatar

Comments

4

One potential big difference between sleep/interrupt and wait/notify is that

Generating an exception when not needed is inefficient. If you have threads communicating with each other at a high rate, then it would be generating a lot of exceptions if you were calling interrupt all the time, which is a total waste of CPU.

Ravindra babu's user avatar
Ravindra babu
39.1k11 gold badges258 silver badges222 bronze badges
answeredMay 18, 2013 at 22:26
Mark's user avatar

2 Comments

+1, A valid point actually, though arguing on theinternals of implementations may be more relevant to performance analysis...
In other words the overhead of creating exceptions might be significantly smaller than the overhead of the system's implementation of one vs the other.
3

You are correct - Sleep() causes that thread to "sleep" and the CPU will go off and process other threads (otherwise known as context switching) wheras I believe Wait keeps the CPU processing the current thread.

We have both because although it may seem sensible to let other people use the CPU while you're not using it, actualy there is an overhead to context switching - depending on how long the sleep is for, it can be more expensive in CPU cycles to switch threads than it is to simply have your thread doing nothing for a few ms.

Also note that sleep forces a context switch.

Also - in general it's not possible to control context switching - during the Wait the OS may (and will for longer waits) choose to process other threads.

oxbow_lakes's user avatar
oxbow_lakes
135k56 gold badges323 silver badges451 bronze badges
answeredJun 24, 2009 at 7:02
Justin's user avatar

3 Comments

wait() doesn't keep the CPU processing the current thread. It is like sleep in that it causes a context switch as well:javamex.com/tutorials/threads/context_switch.shtml. I've been asking for half a year all around stackoverflow and it seems like no one knows what's the difference between wait/notify vs sleep/interrupt.
although sleep does not keep CPU in processing of the current thread, I think, it is anyway a little bit a burden for the CPU, because CPU needs track the moment of when to end the sleep. It does not have that external trigger like "notify" in wait. No?
@VladimirNabokov, The external trigger isinterrupt. The ending time isn inwait(n). ¶¶ It's been 8 years now and still no one has the answer !
3

The methods are used for different things.

Thread.sleep(5000);   // Wait until the time has passed.Object.wait();        // Wait until some other thread tells me to wake up.

Thread.sleep(n)can be interrupted, but Object.wait()must be notified.It's possible to specify the maximum time to wait:Object.wait(5000) so it would be possible to usewait to, er,sleep but then you have to bother with locks.

Neither of the methods uses the cpu while sleeping/waiting.

The methods are implemented using native code, using similar constructs but not in the same way.

Look for yourself:Is the source code of native methods available? The file/src/share/vm/prims/jvm.cpp is the starting point...

answeredMay 11, 2013 at 6:15
KarlP's user avatar

2 Comments

Thread.sleep timing can also be set to indefinite. Object.wait timing can also be set to definite. This answer doesn't explain why we need 2 hammers that do the same thing.
Thread.sleep(big_num)must be interrupted.Object.wait(small_num)can be notified.
3

Wait() and sleep() Differences?

Thread.sleep() Once its work completed then only its release the lock to everyone. until its never release the lock to anyone.

  Sleep() take the key, its never release the key to anyone, when its work completed then only its release then only take the key waiting stage threads.

Object.wait() When its going to waiting stage, its will be release the key and its waiting for some of the seconds based on the parameter.

For Example:

you are take the coffee in yours right hand, you can take another anyone of the same hand, when will your put down then only take another object same type here. also. this is sleep() you sleep time you didn't any work, you are doing only sleeping.. same here also.

wait(). when you are put down and take another one mean while you are waiting , that's wait

you are play movie or anything in yours system same as player you can't play more than one at a time right, thats its here, when you close and choose another anyone movie or song mean while is called wait

answeredMay 6, 2014 at 12:51
VISALIG's user avatar

Comments

3

wait releases the lock andsleep doesn't. A thread in waiting state is eligible for waking up as soon asnotify ornotifyAll is called. But in case ofsleep the thread keeps the lock and it'll only be eligible once the sleep time is over.

Marco Forberg's user avatar
Marco Forberg
2,6445 gold badges24 silver badges33 bronze badges
answeredNov 7, 2014 at 8:53
shikjohari's user avatar

3 Comments

So if the thread is sleeping for 10 seconds and an interrupted exception happens ????
@Geek AnInterruptedException is thrown, just as it says in the Javadoc.
@EJP : Are you the same EJP who was in sun.java.com forums ? Atleast your score suggests same :-)
2

sleep() method causes the current thread to move from running state to block state for a specified time. If the current thread has the lock of any object then it keeps holding it, which means that other threads cannot execute any synchronized method in that class object.

wait() method causes the current thread to go into block state either for a specified time or until notify, but in this case the thread releases the lock of the object (which means that other threads can execute any synchronized methods of the calling object.

dkar's user avatar
dkar
2,1531 gold badge19 silver badges30 bronze badges
answeredJul 14, 2013 at 20:01
User10001's user avatar

Comments

2

In my opinion, the main difference between both mechanisms is that sleep/interrupt is the most basic way of handling threads, whereaswait/notify is an abstraction aimed to do thread inter-communication easier. This means that sleep/interrupt can do anything, but that this specific task is harder to do.

Why is wait/notify more suitable? Here are some personal considerations:

  1. It enforces centralization. It allows to coordinate the communication between a group of threads with a single shared object. This simplifies the work a lot.

  2. It enforces synchronization. Because it makes the programmer wrap the call to wait/notify in a synchronized block.

  3. It's independent of the thread origin and number. With this approach you can add more threads arbitrarily without editing the other threads or keeping a track of the existing ones. If you used sleep/interrupt, first you would need to keep the references to the sleeping threads, and then interrupt them one by one, by hand.

An example from the real life that is good to explain this is a classic restaurant and the method that the personnel use to communicate among them: The waiters leave the customer requests in a central place (a cork board, a table, etc.), ring a bell, and the workers from the kitchen come to take such requests. Once that there is any course ready, the kitchen personnel ring the bell again so that the waiters are aware and take them to the customers.

answeredJan 30, 2014 at 17:15
negora's user avatar

Comments

2

Example about sleep doesn’t release lock and wait does

Here there are two classes :

  1. Main : Contains main method and two threads.
  2. Singleton : This is singleton class with two static methods getInstance() and getInstance(boolean isWait).

    public class Main {private static Singleton singletonA = null;private static Singleton singletonB = null;public static void main(String[] args) throws InterruptedException {Thread threadA = new Thread() {    @Override    public void run() {        singletonA = Singleton.getInstance(true);    }};Thread threadB = new Thread() {    @Override    public void run() {        singletonB = Singleton.getInstance();        while (singletonA == null) {            System.out.println("SingletonA still null");        }        if (singletonA == singletonB) {            System.out.println("Both singleton are same");        } else {            System.out.println("Both singleton are not same");        }    }};threadA.start();threadB.start(); }}

and

public class Singleton {    private static Singleton _instance;    public static Singleton getInstance() {    if (_instance == null) {        synchronized (Singleton.class) {            if (_instance == null)                _instance = new Singleton();        }    }    return _instance;}public static Singleton getInstance(boolean isWait) {    if (_instance == null) {        synchronized (Singleton.class) {            if (_instance == null) {                if (isWait) {                    try {                        // Singleton.class.wait(500);//Using wait                        Thread.sleep(500);// Using Sleep                        System.out.println("_instance :"                                + String.valueOf(_instance));                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }                _instance = new Singleton();            }        }    }    return _instance; }}

Now run this example you will get below output :

_instance :nullBoth singleton are same

Here Singleton instances created by threadA and threadB are same. It means threadB is waiting outside until threadA release it’s lock.

Now change the Singleton.java by commenting Thread.sleep(500); method and uncommenting Singleton.class.wait(500); . Here because of Singleton.class.wait(500); method threadA will release all acquire locks and moves into the “Non Runnable” state, threadB will get change to enter in synchronized block.

Now run again :

SingletonA still nullSingletonA still nullSingletonA still null_instance :com.omt.sleepwait.Singleton@10c042abSingletonA still nullSingletonA still nullSingletonA still nullBoth singleton are not same

Here Singleton instances created by threadA and threadB are NOT same because of threadB got change to enter in synchronised block and after 500 milliseconds threadA started from it’s last position and created one more Singleton object.

answeredDec 1, 2014 at 11:06
Dhiral Pandya's user avatar

Comments

2

Should be called from synchronized block :wait() method is always called from synchronized block i.e.wait() method needs to lock object monitor before object on which it is called. Butsleep() method can be called from outside synchronized block i.e.sleep() method doesn’t need any object monitor.

IllegalMonitorStateException : ifwait() method is called without acquiring object lock thanIllegalMonitorStateException is thrown at runtime, butsleep() method never throws such exception.

Belongs to which class :wait() method belongs tojava.lang.Object class butsleep() method belongs tojava.lang.Thread class.

Called on object or thread :wait() method is called on objects butsleep() method is called on Threads not objects.

Thread state : whenwait() method is called on object, thread that holded object’s monitor goes from running to waiting state and can return to runnable state only whennotify() ornotifyAll() method is called on that object. And later thread scheduler schedules that thread to go from from runnable to running state. whensleep() is called on thread it goes from running to waiting state and can return to runnable state when sleep time is up.

When called from synchronized block : whenwait() method is called thread leaves the object lock. Butsleep() method when called from synchronized block or method thread doesn’t leaves object lock.

For MoreReference

answeredDec 20, 2015 at 3:27
AVI's user avatar

1 Comment

probably a better reference URL than that one.
1

wait() is given inside a synchronized method whereassleep() is given inside a non-synchronized method becausewait() method release the lock on the object butsleep() oryield() does release thelock().

alecxe's user avatar
alecxe
476k127 gold badges1.1k silver badges1.2k bronze badges
answeredMay 11, 2013 at 5:26
Aravind Mano's user avatar

1 Comment

sleep() can be inside asynchronized block or method. Answer explains nothing.
1

From oracle documentation page onwait() method ofObject:

public final void wait()
  1. Causes the current thread to wait until another thread invokes thenotify() method or thenotifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the callwait(0).
  2. The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up
  3. interrupts and spurious wakeups are possible
  4. This method should only be called by a thread that is the owner of this object's monitor

This method throws

  1. IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.

  2. InterruptedException - if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.

From oracle documentation page onsleep() method ofThread class:

public static void sleep(long millis)
  1. Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
  2. The thread does not lose ownership of any monitors.

This method throws:

  1. IllegalArgumentException - if the value of millis is negative

  2. InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

Other key difference:

wait() is a non-static method (instance method) unlike static methodsleep() (class method).

answeredMay 13, 2016 at 16:33
Ravindra babu's user avatar

Comments

1
  • The methodwait(1000) causes the current thread to sleepup to one second.
  • The call tosleep(1000) causes the current thread to sleep forexactly 1 second.
    • Alsosleeping thread doesn't hold lock any resource. But waiting thread does.
Ravindra babu's user avatar
Ravindra babu
39.1k11 gold badges258 silver badges222 bronze badges
answeredMay 17, 2013 at 19:55
Rupesh's user avatar

3 Comments

sleep(1000) doesn't guaranty to sleep for exactly 1 second. It may may be interrupted before.
These posts are so confusing. All the other posts on this thread say that a sleeping thread DOES hold the lock and that a waiting thread DOESNT hold the lock. Similarly the post with the diagram implies that calls to notify() wake sleeping threads but other posts (and thread state diagrams) imply that only interrupt() or the timeout period passing do this. I just ordered myself a copy of java concurrency in practice, something I should have read a long time ago!
If Thread.sleep() is called inside synchronized block, it WILL CONTINUE HOLDING THE LOCK for the duration of sleep preventing other threads from entering same synchronized block!!! This answer contains wrong statement about the lock.
1

Actually, all this is clearly described in Java docs (but I realized this only after reading the answers).

http://docs.oracle.com/javase/8/docs/api/index.html :

wait() - The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

sleep() - Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

Ravindra babu's user avatar
Ravindra babu
39.1k11 gold badges258 silver badges222 bronze badges
answeredAug 7, 2013 at 22:34
TT_ stands with Russia's user avatar

Comments

Protected question. To answer this question, you need to have at least 10 reputation on this site (not counting theassociation bonus). The reputation requirement helps protect this question from spam and non-answer activity.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.