yield Method in Java

yield() method in Java is used for current thread execution to give a chance for waiting for a thread of the same priority. If all waiting threads have low priority or there is no waiting thread then the current thread execution will continue.

If multiple threads are waiting with the same priority then with thread will chance of execution no one can decide exactly which Thread is going to get a chance for execution. It completely depends upon the Thread scheduler. The Thread execution which is yielded(), when it is again going to get a chance for execution depends upon the Thread scheduler.

public class YieldMethod extends Thread{
    @Override
    public void run() {
        for(int i=0;i<10;i++){
            Thread.yield();
            System.out.println("Child Thread is executing");
        }
    }
}
         class TheCodeData{
             public static void main(String[] args) {
                 YieldMethod obj = new YieldMethod();
                 obj.start();

                 for(int i=0;i<4;i++){
                     System.out.println("Main Thread is executing");

                 }
             }

         }
yield Method in Java

Note-

Some platforms would not provide proper support for the yield() method.

Similar Java Tutorials

Leave a Comment