Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

yield
java threads
java programming
java
communitycreator

What is the Thread.yield() function in Java?

AKASH BAJWA

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The static function Thread.yield() interrupts the scheduler that the current thread is willing to yield the CPUCentral Processing Unit utilization.

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 class
class Edpresso extends Thread {
public void run() {
int i=0;
while(i!= 2){
// After calling yield(), it will stop Edpresso execution
Thread.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 execution
thread.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 Edpresso class from the Thread class.
  • Line 8: We invoke the yield() function on the current thread.
  • Line 18: We create a new thread instance of the Edpresso type.
  • Line 20: We start the thread that we created in line 18 to test the working of the yield() function.

RELATED TAGS

yield
java threads
java programming
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring