Difference between wait() and sleep()



One key difference is that:

while sleeping a Thread does not release the locks (it holds),

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

while waiting releases the lock on the object that wait() is called on.

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

 Difference between sleep() and wait() in human terms:

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.

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


Let clarity some key notes:

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 the same Object one by one.
  • sleep(): when synchronized multiple threads wait for the sleepover of the sleeping thread.

Hold lock:

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

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.

Example:

package com.example.TestApp;public class SleepingThread{    public static void main( String[] args ) throws InterruptedException    {        System.out.println( "Hello World!" );        Thread t1 = new Thread(new Producer());        t1.start();        Thread.sleep(50000);        t1.join();         System.out.println( "End of Main Thread" );    }}class Producer implements Runnable {    public void run() {        try {         synchronized(this) {                    wait();                    System.out.println( "End of Producer Thread" );            }              } catch(InterruptedException e) {     }  }}