sleep()和yield()的區(qū)別
1) sleep()使當(dāng)前線程進入停滯狀態(tài),所以執(zhí)行sleep()的線程在指定的時間內(nèi)肯定不會執(zhí)行;yield()只是使當(dāng)前線程重新回到可執(zhí)行狀態(tài),所以執(zhí)行yield()的線程有可能在進入到可執(zhí)行狀態(tài)后馬上又被執(zhí)行。
2) sleep()可使優(yōu)先級低的線程得到執(zhí)行的機會,當(dāng)然也可以讓同優(yōu)先級和高優(yōu)先級的線程有執(zhí)行的機會;yield()只能使同優(yōu)先級的線程有執(zhí)行的機會。
例15:
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();
}
}
運行結(jié)果為:
t1 : 0
t1 : 1
t2 : 0
t1 : 2
t2 : 1
t1 : 3
t2 : 2
t2 : 3
由結(jié)果可見,通過sleep()可使優(yōu)先級較低的線程有執(zhí)行的機會。注釋掉代碼(2),并去掉代碼(1)的注釋,結(jié)果為:
t1 : 0
t1 : 1
t1 : 2
t1 : 3
t2 : 0
t2 : 1
t2 : 2
t2 : 3
可見,調(diào)用yield(),不同優(yōu)先級的線程永遠(yuǎn)不會得到執(zhí)行機會。
1) sleep()使當(dāng)前線程進入停滯狀態(tài),所以執(zhí)行sleep()的線程在指定的時間內(nèi)肯定不會執(zhí)行;yield()只是使當(dāng)前線程重新回到可執(zhí)行狀態(tài),所以執(zhí)行yield()的線程有可能在進入到可執(zhí)行狀態(tài)后馬上又被執(zhí)行。
2) sleep()可使優(yōu)先級低的線程得到執(zhí)行的機會,當(dāng)然也可以讓同優(yōu)先級和高優(yōu)先級的線程有執(zhí)行的機會;yield()只能使同優(yōu)先級的線程有執(zhí)行的機會。
例15:
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();
}
}
運行結(jié)果為:
t1 : 0
t1 : 1
t2 : 0
t1 : 2
t2 : 1
t1 : 3
t2 : 2
t2 : 3
由結(jié)果可見,通過sleep()可使優(yōu)先級較低的線程有執(zhí)行的機會。注釋掉代碼(2),并去掉代碼(1)的注釋,結(jié)果為:
t1 : 0
t1 : 1
t1 : 2
t1 : 3
t2 : 0
t2 : 1
t2 : 2
t2 : 3
可見,調(diào)用yield(),不同優(yōu)先級的線程永遠(yuǎn)不會得到執(zhí)行機會。