【本節目标】
通過閱讀本節内容,你将學會使用sleep方法使線程休眠、使用interrupt方法強行中斷線程,并掌握當線程被中斷時進行中斷異常的方法。
線程的休眠
如果希望某個線程可以暫緩執行,那麼就可以使用休眠的處理,在Thread類中定義的休眠方法如下:
public static void sleep(long millis) throws InterruptedException
public static void sleep(long millis, int nanos) throws InterruptedException
在進行休眠的時候有可能會産生中斷異常“InterruptedException”,中斷異常屬于Exception的子類,是以該異常必須進行處理。
範例:觀察休眠處理
public class ThreadDemo {
public static void main(String[] args) throws Exception {
new Thread(() -> {
for (int x = 0; x < 10; x++) {
try {
Thread.sleep(1000); //暫緩執行
}catch (InterruptedException e){
}
System.out.println(Thread.currentThread().getName() + "、x = " + x);
}
},"線程對象").start();
}
}

圖一 休眠處理執行結果
休眠的主要特點是可以自動實作線程的喚醒,以繼續進行後續的處理。但是需要注意的是,如果現在有多個線程對象,那麼休眠也是有先後順序的。
範例:産生多個線程對象進行休眠處理
public class ThreadDemo {
public static void main(String[] args) throws Exception {
Runnable run=() -> {
for (int x = 0; x < 10; x++) {
System.out.println(Thread.currentThread().getName() + "、x = " + x);
try {
Thread.sleep(1000); //暫緩執行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
for (int num = 0; num < 5; num++) {
new Thread(run, "線程對象 - " + num).start();
}
}
}
圖二 多線程休眠處理
此時将産生5個線程對象,并且這5個線程對象執行的方法體是相同的。此時從程式執行的感覺上好像是若幹個線程一起進行了休眠,而後一起進行了自動喚醒,但是實際上是有差别的。
圖三 多線程處理
線程中斷
在之前發現線程的休眠提供有一個中斷異常,實際上就證明線程的休眠是可以被打斷的,而這種打斷肯定是由其他線程完成的。在Thread類裡面提供有這種中斷執行的處理方法:
判斷線程是否被中斷:public boolean isInterrupted();
中斷線程執行:public void interrupt();
範例:觀察線程的中斷處理操作
public class ThreadDemo {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(() -> {
System.out.println("*** 72個小時的瘋狂我需要睡覺補充精力。");
try {
Thread.sleep(10000); //預計準備休眠10秒
System.out.println("****** 睡足了,可以出去繼續禍害别人了。");
} catch (InterruptedException e) {
System.out.println("不要打擾我睡覺,我會生氣的。");
}
});
thread.start(); //開始睡
Thread.sleep(1000);
if (thread.isInterrupted()==false) { //該線程中斷了嗎?
System.out.println("我偷偷地打擾一下你的睡眠");
thread.interrupt(); //中斷執行
}
}
}
所有正在執行的線程都是可以被中斷的,中斷的線程必須進行異常的處理。
想學習更多的Java的課程嗎?從小白到大神,從入門到精通,更多精彩不容錯過!免費為您提供更多的學習資源。
本内容視訊來源于
阿裡雲大學 下一篇:迅速讀懂Java線程的交通規則 | 帶你學《Java語言進階特性》之八 更多Java面向對象程式設計文章檢視此處