yield函數概念:java
當調用Thread.yield() 函數時,會給線程調度器一個當前線程願意讓出CPU使用的暗示,可是線程調度器可能會忽略這個暗示。ide
public class YieldDemo { public static void main(String[] args) { Runnable yieldTask = new Runnable() { @Override public void run() { for(int i = 1; i <= 10; i++){ System.out.println(Thread.currentThread().getName() + i) ; if(i == 5){ Thread.yield(); } } } }; Thread t1= new Thread(yieldTask,"A"); Thread t2 = new Thread(yieldTask,"B"); t1.start(); t2.start(); } }
打印結果:函數
A1 A2 A3 A4 A5 A6 A7 A8 A9 B1 A10 B2 B3 B4 B5 B6 B7 B8 B9 B10
能夠發現A5後面是A6,並無讓出CPU線程
再執行一次blog
A1 B1 A2 A3 A4 A5 B2 A6 A7 A8 A9 A10 B3 B4 B5 B6 B7 B8 B9 B10
能夠發現A5後面是B2,交出了CPU執行get