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  .  co  m*/


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");
  }

}




















Home »
  Java Tutorial »
    java.lang »




Boolean
Byte
Character
Class
Double
Enum
Float
Integer
Long
Math
Number
Object
Package
Process
ProcessBuilder
Runnable
Runtime
SecurityManager
Short
StackTraceElement
StrictMath
String
StringBuffer
StringBuilder
System
Thread
ThreadGroup
ThreadLocal
Throwable