Java編程語言在使用中有不少須要咱們學習的,下面咱們就來看看sleep()和yield()的區別之間的區別,但願你們在詳細學習中有所收穫。只有在不斷的學習才能更好的使用。 java
1) sleep()使當前線程進入停滯狀態,因此執行sleep()的線程在指定的時間內確定不會執行;yield()只是使當前線程從新回到可執行狀態,因此執行yield()的線程有可能在進入到可執行狀態後立刻又被執行。 編程
2) sleep()可以使優先級低的線程獲得執行的機會,固然也能夠讓同優先級和高優先級的線程有執行的機會;yield()只能使同優先級的線程有執行的機會。 編程語言
class TestThreadMethod extends Thread{ public static int shareVar = 0; public TestThreadMethod(String name){ super(name); } public void run(){ for(int i=0; i<4; i++){ System.out.print(Thread.currentThread().getName()); System.out.println(" : " + i); //Thread.yield(); (1) /* (2) */ try{ Thread.sleep(3000); } catch(InterruptedException e){ System.out.println("Interrupted"); }}} } public class TestThread{ public static void main(String[] args){ TestThreadMethod t1 = new TestThreadMethod("t1"); TestThreadMethod t2 = new TestThreadMethod("t2"); t1.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MIN_PRIORITY); t1.start(); t2.start(); } }
運行結果爲: 學習
t1 : 0 t1 : 1 t2 : 0 t1 : 2 t2 : 1 t1 : 3 t2 : 2 t2 : 3
由結果可見,經過sleep()可以使優先級較低的線程有執行的機會。註釋掉代碼(2),並去掉代碼(1)的註釋,結果爲: spa
t1 : 0 t1 : 1 t1 : 2 t1 : 3 t2 : 0 t2 : 1 t2 : 2 t2 : 3
可見,調用yield(),不一樣優先級的線程永遠不會獲得執行機會。 線程
以上就是對Java編程語言的相關介紹,但願你們有所幫助。 code