What is the Thread.yield() function in Java?
The static function Thread.yield() interrupts the scheduler that the current thread is willing to yield the
Yield is a heuristic or triggering of the CPU to improve the relative progression between two threads or processes. Otherwise, CPU over-utilization occurs.
Note: Programmers use this method, especially for testing and debugging purposes.
Syntax
static void yield()
Return value
This function does not return any value(s).
Code example
The code snippet given below demonstrates how the yield() function works:
// Demo program to check yield() method// Edpresso class which is implementing Thread classclass Edpresso extends Thread {public void run() {int i=0;while(i!= 2){// After calling yield(), it will stop Edpresso executionThread.yield();System.out.println("Edpresso thread started:" + Thread.currentThread().getName());i++;}System.out.println("Edpresso thread ended:" + Thread.currentThread().getName());}}// Main class to create another thread.class Main {public static void main(String[] args) {Edpresso thread = new Edpresso();// starting Edpresso thread executionthread.start();int i=0;while(i!= 2) {System.out.println("Main thread started:" + Thread.currentThread().getName());i++;}System.out.println("Main thread ended:" + Thread.currentThread().getName());}}
Code explanation
- Line 3: We inherit the
Edpressoclass from theThreadclass. - Line 8: We invoke the
yield()function on the current thread. - Line 18: We create a new thread instance of the
Edpressotype. - Line 20: We start the thread that we created in line 18 to test the working of the
yield()function.