Thread.sleep(500);
當前線程在cpu中睡個500ms,讓給別的線程去運行前酿。sleep完回到就緒狀態(tài)Thread.yield();
讓出cpu一會患雏,返回就緒狀態(tài),放入等待隊列中罢维,下一個執(zhí)行的線程可能是別的線程淹仑,也有可能還是自己。join();
比如有2個線程t1
,t2
,在t1
內調用了t2.join();
那么從這點開始t1
要等t2
運行完肺孵,才能繼續(xù)執(zhí)行匀借。
線程狀態(tài)
sleep(),wait(),join()在執(zhí)行過程中都能被interrupt,中斷標志設置為true,若是有捕獲InterruptedException平窘,在異常中自己處理吓肋。捕獲到這個異常然后這個異常拋出之后,又會馬上將線程中斷標識重置為false初婆。
public class TestInterrupt {
public static void main(String[] args){
Thread thread = new Thread(() -> {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println();
System.out.println("end.....");
});
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread.isInterrupted());
thread.interrupt();
System.out.println(thread.isInterrupted());
}
}
執(zhí)行后輸出:
false
false
end.....
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.mashibing.mytest.TestInterrupt.lambda$main$0(TestInterrupt.java:11)
at java.lang.Thread.run(Thread.java:748)