- Whenever a thread calls java.lang.Thread.yield method, it gives hint to the thread scheduler that it is ready to pause its execution. Thread scheduler is free to ignore this hint.
- If any thread executes yield method , thread scheduler checks if there is any thread with same or high priority than this thread. If processor finds any thread with higher or same priority then it will move the current thread to Ready/Runnable state and give processor to other thread and if not – current thread will keep executing.
场景一:
class MyThread extends Thread { public void run() { for (int i = 0; i < 5; i++) System.out.println(Thread.currentThread().getName() + " in control"); } } // Driver Class public class YieldDemo { public static void main(String[] args) { MyThread t = new MyThread(); t.setPriority(Thread.MAX_PRIORITY); t.start(); for (int i = 0; i < 5; i++) { // Thread.yield(); System.out.println(Thread.currentThread().getName() + " in control"); } } }
输出 :
main in control
main in control
main in control
main in control
main in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
结果输出并不唯一,但基本主线程先结束。
场景二:
class MyThread extends Thread { public void run() { for (int i = 0; i < 5; i++) System.out.println(Thread.currentThread().getName() + " in control"); } } // Driver Class public class YieldDemo { public static void main(String[] args) { MyThread t = new MyThread(); t.setPriority(Thread.MAX_PRIORITY); t.start(); for (int i = 0; i < 5; i++) { Thread.yield(); System.out.println(Thread.currentThread().getName() + " in control"); } } }
去掉Thread.yield()注释。输出:
main in control
main in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
main in control
main in control
main in control