Java Thread Yield


 

Java Thread Yield

In this segment of tutorial we will learn about the yield() static method yield.Then We will create an example and use the yield static method it add will see the program behaviour.

In this segment of tutorial we will learn about the yield() static method yield.Then We will create an example and use the yield static method it add will see the program behaviour.

  • Java Thread yield is a static method
  • It works on same priority threads
  • It makes same priority thread from running to runnable state.
  • Then other same priority thread comes to running state from runnable state


Java Yield Thread Example
public class yield1 implements Runnable {

	@Override
	public void run() {
		for (int x = 1; x <= 4; x++) {
			if (x == 2) {
				Thread.yield();
			} else {

				System.out.println(x + "Thread name is  "
						+ Thread.currentThread().getName());
			}
		}
	}

	public static void main(String[] args) {
		Thread t1 = new Thread(new yield1());
		Thread t2 = new Thread(new yield1());
		Thread t3 = new Thread(new yield1());
		t1.start();
		t2.start();
		t3.start();
	}
}

Output :

1Thread name is Thread-0 1Thread name is Thread-2 1Thread name is Thread-1 3Thread name is Thread-0 4Thread name is Thread-0 3Thread name is Thread-1 4Thread name is Thread-1 3Thread name is Thread-2 4Thread name is Thread-2

Ads