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

Code Factory
2 min readMay 29, 2020

--

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()/*
Source : https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#yield--
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.
Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU.
Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.
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.
It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.
*/
package com.example.thread;/**
* @author code.factory
*
*/
public class ThreadYield {
public static void main(String... args) {
MyThread t = new MyThread();
t.start();
for(int i=0; i<5; i++) {
System.out.println("Main Thread");
}
}
}
class MyThread extends Thread {
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Child Thread");
Thread.yield(); // #1
}
}
}

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.

--

--