Java — Java.lang.Thread.yield() Method | Code Factory

Index Page : Link

Donate : Link

WordPress Blog : Link

  • yield() method causes to pause current executing thread to give the chance for waiting threads of same priority.
  • If there is no waiting thread or all waiting thread have low priority then same thread can continue it’s execution.
  • If multiple threads are waiting with same priority then which waiting thread will get the chance we can’t expect, It depends on thread schedular.
  • The thread which is yielded, when it will get chance once again it depends on thread schedular and we can’t expect exactly.
public static void yield()
package com.example.thread;

Output :

Main Thread
Main Thread
Main Thread
Child Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
  • In the above program if we are commenting line #1 then both the threads will be executed simultaneously and we can’t expect which thread will complete first.
  • If we are not commenting line #1 then child thread aways call yield() method because of that main thread will get chance more number of times and the chance of completing main thread 1st is high.
  • Some platform wouldn’t provide proper suport for yield() method.