What is yield () method in java multithreading?

(Last Updated On: March 9, 2017)

Answer:

When a thread calls yield() method in Java, this means, the thread wants to relinquish the control over processor and give it to other priorities threads while not doing anything useful / waiting for input .

In a simple word when you call Thread.yield(), thread leaves CPU and goes back to queue and wait. And, as soon as it gets its chance again, it executes.

Notes:

First of all we need to understand meaning of yield. Yield means “to relinquish possession of (something)” e.g In a multithreading context, one thread can ‘yield'(give up) the processor to other threads when it cannot do anything useful – while waiting for input or for some condition to become true.

Some important points

  • Yielding is a hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.
  • It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions.

 

One more quote to get a clearer picture:

To help ensure that other threads in the VM get a turn to run on the processor, a thread can voluntarily give up its turn early. If a thread invokes the static method Thread.yield(), the thread scheduler will swap it off the processor and allow another thread to run. It is likely (but not guaranteed) that only threads having a priority equal to or greater than the one that yielded control will be considered by the thread scheduler.                                                                       – – Paul Hyde.