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.
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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store