In Java, the yield() method is a static method in the Thread class that allows a thread to voluntarily give up its current CPU time slice, allowing other threads to run. When a thread calls the yield() method, it indicates that it is willing to be preempted by the scheduler and put back in the ready queue, allowing other threads to run.
The yield() method does not cause a thread to stop running, but it does allow the scheduler to select another thread to run. The selected thread may be the same thread that called yield(), or it may be another thread. Therefore, calling yield() does not guarantee that other threads will run immediately, but it increases the chances of other threads getting CPU time.
Here's an example that demonstrates how to use the yield() method in Java:
public class YieldExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 1 - " + i);
Thread.yield();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 2 - " + i);
Thread.yield();
}
});
thread1.start();
thread2.start();
}
}
In this example, we create two threads, thread1 and thread2, each of which runs a loop that prints its thread name and a number from 1 to 5. Inside the loop, each thread calls the yield() method, allowing the scheduler to select another thread to run.
When we run the main() method, we start both threads and see that they alternate between printing their output. By calling yield(), each thread gives up its CPU time slice and allows the other thread to run, resulting in a more balanced sharing of CPU time between the threads.
It's important to note that calling yield() does not guarantee fair sharing of CPU time between threads. The scheduler may still choose to favor one thread over another, depending on the system load and other factors. Therefore, yield() should be used judiciously and only when necessary, and other synchronization mechanisms, such as locks or semaphores, should be used to coordinate access to shared resources.