Java Concurrency – yield() method

JavaObject Oriented ProgrammingProgramming

The yield function

The function tries to ensure that the thread that is more important runs first rather than a thread that is taking too much time to get executed and is not important too.

When thread calls the java.lang.Thread.yield method, it is an indication for the thread scheduler to pause its execution. The thread scheduler chooses to accept or ignore this indication.

If the thread executes the ‘yield’ function, the scheduler checks to see if a thread with same or higher priority is present. If so, the current thread is moved to runnable or ready state and that thread is given processor resources.

Syntax of yield function

public static native void yield()

Let us see an example −

Example

 Live Demo

import java.lang.*;
class Demo extends Thread{
   public void run(){
      for (int i=0; i<3 ; i++)
      System.out.println("In control of " + Thread.currentThread().getName() + " thread");
   }
}
public class Demo_one{
   public static void main(String[]args){
      Demo my_obj = new Demo();
      my_obj.start();
      for (int i=0; i<3; i++){
         Thread.yield();
         System.out.println("In control of " + Thread.currentThread().getName() + " thread");
      }
   }
}

Output

In control of main thread
In control of main thread
In control of main thread
In control of Thread-0 thread
In control of Thread-0 thread
In control of Thread-0 thread

A class named Demo extends the Thread class. Here, a ‘run’ function is defined that iterates over a set of elements and gets the name of the thread using the ‘getName’ function. A class named ‘Demo_one’ defines the main function where a new instance is created and it is begun using the ‘start’ function. Here also, elements are iterated over and the yield function is called on the thread.

  • Once the thread has completed execution using yield method, there are many threads which compete for processor resources. There is no way to specify which thread would execute first.

  • Once the thread executes the yield method, it goes from Running state to the Runnable state.

  • The yield method can be used only if the platform supports pre-emptive scheduling.

  • When the thread pauses during its execution, there is no way to ensure that it would get a chance soon or later, it all depends on the scheduling algorithm and the thread scheduler.

raja
Published on 04-Jul-2020 08:58:21
Advertisements