Wait() vs. Sleep()

Wait and sleep method are completely different to each other

  • wait() & notify(): method for inter thread communication.
  • sleep(): introducing small pause during thread execution.

Screen Shot 2016-07-26 at 2.49.35 PM

wait() & notify()

  • wait() method puts a thread on wait
    • For example, in Producer Consumer problem, producer thread should wait if Queue is full or Consumer thread should wait if Queue is empty.
  • notify()  & notifyAll() method is used to wake up waiting thread by communicating that waiting condition is over now
    • For example, once producer thread puts an item on empty queue it can notify Consumer thread that Queue is not empty any more.
    • notify(): wakes up one thread
    • notifyAll(): wakes up all the threads (use this when you are not sure which one to use)
Example...
/*
   Until pizza arrives, eatPiazza will in wait
   If pizzaGuy() executed, it will wake up eatPiazza()
   by using notifyAll();
*/
class MyHouse{
   private boolean pizzaArrived = false;
   
   public void eatPizza(){
      synchronized(this){
         while(!pizzaArrived){
            wait();
         }
      }
      System.out.println("yumyum...");
   }

   public void pizzaGuy(){
      synchronized(this){
         this.pizzaArrived = true;
         notifyAll();
      }
   }
}

sleep()

  • sleep() hold a lock, doesn’t release any lock or monitor while sleeping.
  • When a Thread goes to Sleep it can be either wake up normally after sleep duration elapsed or it can be woken up abnormally by interrupting it.
Example...
/*
   It will print out count string one at a time
   with a 3 seconds term
*/
public class Example{
   public static void main(String[] args){
      String count[] = ("One","Two","Three","Four","Five");

      for(int i=0; i<count.length;i++){
         Thread.sleep(3000);             // sleep for 3 seconds
          System.out.println(count[i]);  // printout count string
      }
   }
}

Leave A Comment

Your email address will not be published. Required fields are marked *