
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Concurrency Yield Method
In this article, we will learn that concurrency in Java allows multiple threads to execute simultaneously, sharing system resources efficiently. One of the methods provided in the Thread class for managing thread execution is the yield() method.
What is the yield() Method?
The yield() method is a static method of the Thread class that hints to the thread scheduler that the current thread is willing to pause its execution in favor of other threads of the same or higher priority. It is part of Java's concurrency toolbox and is primarily used for fine-tuning thread execution.
Syntax of yield function ?
public static void yield()
How yield() Works
When a thread calls Thread.yield(), the following occurs ?
- The current thread signals to the thread scheduler that it is willing to yield its current time slice.
- The thread transitions from the "Running" state to the "Ready-to-Run" state.
- The thread scheduler decides whether to schedule another thread or allow the yielding thread to continue execution.
Thread Execution with start() method ?
my_obj.start(); // Starts a new thread executing the run() method.
The thread yield() method hints to the scheduler that the current thread is willing to yield its execution ?
Thread.yield();
Loop in the run() method ?
for (int i = 0; i < 3; i++) {System.out.println("In control of " + Thread.currentThread().getName() + " thread"); }
Example
Below is an example of the Java concurrency yield () method ?
import java.lang.*; class Demo extends Thread{ public void run(){ for (int i=0; i<3 ; i++) System.out.println("In control of " + Thread.currentThread().getName() + " thread"); } } public class Demo_one{ public static void main(String[]args){ Demo my_obj = new Demo(); my_obj.start(); for (int i=0; i<3; i++){ Thread.yield(); System.out.println("In control of " + Thread.currentThread().getName() + " thread"); } } }
Output
In control of main thread In control of main thread In control of main thread In control of Thread-0 thread In control of Thread-0 thread In control of Thread-0 thread
Time Complexity: O(n), where n is the number of iterations in the loops.
Space Complexity: O(1), as the program uses constant extra space regardless of input.
Conclusion
The yield() method in Java provides a way for threads to signal their willingness to relinquish CPU time, facilitating better concurrency. While it can be useful in specific scenarios, its behavior is highly dependent on the thread scheduler and the underlying system.