Both the Thread.yield() and Thread.sleep() methods are used to control the execution of threads in Java. However, they have different functionalities and purposes.
The Thread.yield() method is a hint to the scheduler that the current thread is willing to yield its current use of a processor. It’s a static method that is defined in the Thread class and is used to pause the current thread temporarily, allowing other threads to execute. When a thread calls yield(), it may or may not yield to another thread with the same or higher priority. It only suggests the scheduler that the current thread has no objection to other threads running, but it doesn’t guarantee that other threads will actually execute.
Here is an example code that demonstrates the Thread.yield() method in action:
class YieldExample implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName() + " started");
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
Thread.yield();
}
System.out.println(Thread.currentThread().getName() + " finished");
}
}
public class Main {
public static void main(String[] args) {
YieldExample ye = new YieldExample();
Thread t1 = new Thread(ye, "Thread 1");
Thread t2 = new Thread(ye, "Thread 2");
t1.start();
t2.start();
}
}
The output of this code may vary from run to run, but it should be something like this:
Thread 1 started
Thread 2 started
Thread 1: 1
Thread 2: 1
Thread 1: 2
Thread 2: 2
Thread 1: 3
Thread 2: 3
Thread 1: 4
Thread 2: 4
Thread 1: 5
Thread 2: 5
Thread 1 finished
Thread 2 finished
As you can see, both threads execute simultaneously, and the yield() method allows them to share processor time fairly.
On the other hand, the Thread.sleep() method is used to pause the current thread for a specified amount of time. It’s also a static method defined in the Thread class, and it’s commonly used to simulate a long-running task, or to create a delay between actions. When a thread calls sleep(), it is guaranteed to be suspended for at least the specified amount of time, and other threads can execute during this time.
Here’s an example code that demonstrates the Thread.sleep() method in action:
public class SleepExample {
public static void main(String[] args) {
System.out.println("Task started");
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Task finished");
}
}
This code outputs:
Task started
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Task finished
As you can see, the loop inside the main method runs for 5 iterations, pausing for 1 second between each iteration using the sleep() method.
In summary, the Thread.yield() method is used to give other threads a chance to execute, while the Thread.sleep() method is used to pause the current thread for a specified amount of time.