The static method Thread#yield()
causes the current thread to yield its current use of a processor.
In other words the current thread may stop executing momentarily to give chance to other competing threads having the same priorities.
public class ThreadYieldExample {
public static void main(String[] args) {
Task task1 = new Task(true);
new Thread(task1).start();
Task task2 = new Task(false);
new Thread(task2).start();
}
private static class Task implements Runnable {
private int counter;
private final boolean shouldYield;
private Task(boolean shouldYield) {
this.shouldYield = shouldYield;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " started.");
for (int i = 0; i < 1000; i++) {
counter++;
if(shouldYield){
Thread.yield();
}
}
System.out.println(Thread.currentThread().getName() + " ended.");
}
}
}
In above example we are yielding the first thread in favor of other. As a result the first thread spends less CPU time and it becomes slower than the other, hence ‘Thread-0 ended.’ printed at the end all the time
Output
Thread-0 started.
Thread-1 started.
Thread-1 ended.
Thread-0 ended.
Just like thread priorities, yield method behavior varies from OS to OS. We shouldn’t make coding decisions based on this method. Also this is only a hint, the thread scheduler (on OS level) is free to ignore this hint.