java中什么是Yield給出一個(gè)例子
馬克-to-win:yield英文是屈服投降的意思。 當(dāng)前線程投降就是當(dāng)前線程希望釋放CPU的自己的占用權(quán),( 但系統(tǒng)可以忽略它這個(gè)請(qǐng)求。)參見(jiàn): https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#yield%28%29 其中有這么句話: A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.這樣的話當(dāng)前線程yield時(shí),有時(shí)雖然它自己想讓別的線程執(zhí)行,但系統(tǒng)出于優(yōu)化考慮,可能還是會(huì)讓當(dāng)前的線程繼續(xù)執(zhí)行。這樣的話,yield 就會(huì)有一種不可控的效果,所以并行編程的最佳實(shí)踐建議少用yield。馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
例:1.5.5-本章源碼
class ThreadMark_to_win extends Thread {
private String s;
public ThreadMark_to_win(String s) {
this.s = s;
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
System.out.println(s);
/*當(dāng)前線程希望釋放CPU的自己的占用權(quán),( 但系統(tǒng)可以忽略。) */
Thread.yield();
}
}
}
public class Test {
public static void main(String[] args) {
Thread t1 = new ThreadMark_to_win("線程1");
Thread t2 = new ThreadMark_to_win("線程2");
t1.start();
t2.start();
}
}
運(yùn)行結(jié)果:
線程1
線程2
線程2
線程1
線程1
線程2
線程2
線程1
線程2
線程1
線程1
線程2
線程2
線程1
線程1
線程2
線程2
線程1
線程2
線程1
后續(xù):
馬克-to-win:根據(jù)結(jié)果可以看出:結(jié)果并不是1,2之間穩(wěn)定交替,而是不可控的狀態(tài)。