Difference between wait() and sleep() in java ?

Wait() Method Sleep() Method
wait() Method of thread class goes in waiting state
and it won’t come back automatically until
we call the notify() or notifyAll().
sleep() is a method which is used to pause the process for few seconds or the time we want too.
It is called on Object. It is called on Threads.
It is an instant member of java.lang.Object class. It is a static member of java.lang.Thread class.
wait() releases the lock or monitor. sleep() doesn’t releases the lock or monitor while waiting.
wait() is used for inter-thread communication. sleep() is used to introduce pause on execution, generally.
It must be called within the synchronized blocks. It may be called from within or outside the synchronized block.

wait() Example

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

sleep() Example

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

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,