-2

I need the exact difference between the wait and sleep methods in java. Please give the clear details description about the above methods.

ValLeNain
  • 2,232
  • 1
  • 18
  • 37

1 Answers1

0

sleep(): It is a static method on Thread class. It makes the current thread into the "Not Runnable" state for specified amount of time. During this time, the thread keeps the lock (monitors) it has acquired.

wait(): It is a method on Object class. It makes the current thread into the "Not Runnable" state. Wait is called on a object, not a thread. Before calling wait() method, the object should be synchronized, means the object should be inside synchronized block. The call to wait() releases the acquired lock. Eg:

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.
sai
  • 419
  • 2
  • 7
  • 17