Java Thread: yield() method example

Category : Java | Sub Category : Java Threads | By Prasad Bonam Last updated: 2021-04-20 03:51:42 Viewed : 582


Java Thread: yield() method example

Thread.yield()

This is a static method available in thread class and give the hint for the thread scheduler that the currently running thread is willing to yield the execution time for some other thread.

Thread.yield() will just give a recommendation/hint for the thread scheduler and it is up to thread scheduler to accept or ignore. Therefore we cannot guarantee that calling the Thread.yield() will immediately move the currently running thread not “Not Running  state” and allow some other thread to utilize the CPU time. It will be decided by the thread scheduler.

Please refer the below example about Thread.yield()

 

public class Application
{
public static void main(String[] args)
{
System.out.println("main thread is started");
ThreadA threadA = new ThreadA();
threadA.start();
ThreadB threadB = new ThreadB();
threadB.start();
System.out.println("main thread completed");
}
}
class ThreadA extends Thread
{
public void run()
{
System.out.println("ThreadA is running");
for(int index=0;index<5;index++)
{
System.out.println("ThreadA running on ["+index+"]");
if(index==2){
System.out.println("ThreadA calls Thread.yield() ");
Thread.yield();
}
}
System.out.println("ThreadA completed");
}
}
class ThreadB extends Thread
{
public void run()
{
System.out.println("ThreadB is running");
for(int index=0;index<5;index++){
System.out.println("ThreadB running on ["+index+"]");
}
System.out.println("ThreadB completed");
}
}

 

 

It is very difficult to give the exact output upon running the above code sample as the Thread.yield() method is not guaranteed to run.  Therefore if you run above program few times, you might get different results.

Search
Related Articles

Leave a Comment: