Difference between Yield and Sleep method in Java with Example

We have already shared the difference between Wait and sleep method in java and difference between extends thread and implements runnable. In this article we will see the difference between sleep and yield method in java. This question is related to the topic concurrency. According to  Oracle docs we will discuss the differences , similarities and example of Sleep and Yield method.


Read Also :  LifeCycle of Thread in  Java 


Difference between  Yield and Sleep method in Java with Example

1. Currently executing thread state : Sleep  method causes the currently executing thread to sleep for the number of milliseconds or the  nanoseconds specified in the argument.

There are two overloaded sleep methods

sleep (long milliseconds) , takes milliseconds as an argument.
and
sleep (long milliseconds , int nanoseconds) specifies milliseconds and nanoseconds as an argument.

According to Oracle docs,
Yield method temporarily pauses the currently executing thread to give a chance to the remaining waiting threads of the same priority to execute.
If there is no waiting thread or all the waiting threads of low priority then the current thread will continue its execution.


2. Interrupted Exception : Sleep method throws the Interrupted exception if another thread
interrupts the sleeping thread .  yield method does not throw Interrupted Exception.

3. Give up monitors :  Thread.sleep() method does not cause cause currently executing thread to give up any monitors while yield() method give up the monitors.

Similarities between Yield and Sleep method 

1. Static method : Both yield and sleep method are static method . Hence , they always change the state of currently executing thread .

2. java.lang.Thread : Both yield and sleep method belongs to the java.lang.Thread class.

3. Currently executing thread :  Both methods affect the state of currently executing thread .yield method may pause it while sleep method will stop it for a specified time .


Example of Sleep and Yield method in Java


public class SleepYieldExample {
    
    public static void main(String[] args) { 
 
              // *** Sleep Example ***

         System.out.println(Thread.currentThread.getName() + " is sleeping for 3 seconds ");
              try {
                     Thread.currentThread().sleep(3000);
              } catch (InterruptedException e) {
                     e.printStackTrace();
              }
              System.out.println("Main Thread had enough sleep");

              // *** Yield Example ***
              System.out.println("Yield Example Starts");
                             Thread producer = new Producer();  
      Thread consumer = new Consumer();
       
      producer.setPriority(Thread.MIN_PRIORITY); 
      consumer.setPriority(Thread.MAX_PRIORITY); 
       
      producer.start();
      consumer.start();
  }
}
 
class Producer extends Thread
{
  public void run()
  {
      for (int i = 0; i < 3; i++)
      {
        System.out.println("I am Producer : Producing Item " + i);
        Thread.yield();
      }
  }
}
 
class Consumer extends Thread
{
  public void run()
  {
      for (int i = 0; i < 3; i++)
      {
        System.out.println("I am Consumer : Consuming Item " + i);
        Thread.yield();
      }
  }
}
   

Output :



main is sleeping for 3 Seconds
Main Thread had enough sleep
Yield Example Starts
I am Producer : Producing Item 0
I am Producer : Producing Item 1
I am Producer : Producing Item 2
I am Consumer : Consuming Item 0
I am Consumer : Consuming Item 1
I am Consumer : Consuming Item 2

Recap : Difference between Sleep and Yield Method in Java



SleepYield
Currently Executing Thread StateStops for the specified timePauses the current thread
Interrupted ExceptionYes , throws IENo
Give Up MonitorsNoYes




In case you have any other query regarding difference between sleep and yield method with Example in java, then please mention in the comments .



About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry