Java Data Type Tutorial - Java Thread.yield()








Syntax

Thread.yield() has the following syntax.

public static void yield()

Example

In the following code shows how to use Thread.yield() method.

/*from w w w . j a va 2  s .  c  om*/


class ThreadDemo implements Runnable {
  ThreadDemo(String str) {
    Thread t = new Thread(this, str);
    t.start();
  }

  public void run() {
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    System.out
        .println(Thread.currentThread().getName() + "yielding control...");
    Thread.yield();

    System.out.println(Thread.currentThread().getName()
        + " has finished executing.");
  }

}

public class Main {

  public static void main(String[] args) {
    new ThreadDemo("Thread 1");
    new ThreadDemo("Thread 2");
    new ThreadDemo("Thread 3");
  }

}

The code above generates the following result.