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");
}
}

view raw
Application.java
hosted with ❤ by GitHub

 

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.

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s