Multithreading — Yield

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.

--

--

--

Java Developer and enthusiast

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Spinnaker’s Extensibility Reaches New Heights with Plugins

JIRA Bots: types of bots available today

Nextup JIRA bot

#7DRL Day 5 — Doubt

3 Style Management Tips That Will Save You a Headache in Your Angular App CSS

Create a command line app with dart

One month at uSwitch

How to add Messenger Customer Chat Plugin to your website

Reasonable Spawning Rule- Game Dev Series 45

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
PA

PA

Java Developer and enthusiast

More from Medium

Logging in Java

How to Build Java Applications Today: #58

The Spring Revolutions 2 —Salient Principles

Heap & Stack in Java