Difference between wait() and sleep()

2018-12-31 03:48发布

What is the difference between a wait() and sleep() in Threads?

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

Why do we have both wait() and sleep(): how does their implementation vary at a lower level?

30条回答
萌妹纸的霸气范
2楼-- · 2018-12-31 04:11

wait() is given inside a synchronized method whereas sleep() is given inside a non-synchronized method because wait() method release the lock on the object but sleep() or yield() does release the lock().

查看更多
明月照影归
3楼-- · 2018-12-31 04:13

One key difference not yet mentioned is that while sleeping a Thread does not release the locks it holds, while waiting releases the lock on the object that wait() is called on.

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


synchronized(LOCK) {
    LOCK.wait(); // LOCK is not held
}
查看更多
怪性笑人.
4楼-- · 2018-12-31 04:13

In my opinion, the main difference between both mechanisms is that sleep/interrupt is the most basic way of handling threads, whereas wait/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.

查看更多
冷夜・残月
5楼-- · 2018-12-31 04:13

wait with a timeout value can wakeup upon timeout value elapsed or notify whichever is earlier (or interrupt as well), whereas, a sleep wakes up on timeout value elapsed or interrupt whichever is earlier. wait() with no timeout value will wait for ever until notified or interrupted

查看更多
余生无你
6楼-- · 2018-12-31 04:14

Here, I have listed few important differences between wait() and sleep() 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 of Object class.
  3. wait() is the non-static method - public final void wait() throws InterruptedException { //...}
  4. wait() should be notified by notify() or notifyAll() 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 throw IllegalMonitorStateException

sleep()

  1. sleep() method doesn't release the lock.
  2. sleep() is the method of java.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

查看更多
柔情千种
7楼-- · 2018-12-31 04:14

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.

查看更多
登录 后发表回答