本文的內容所有來自Core Java ui
當線程的run方法執行完最後一條語句並return,或者出現了在方法中未捕獲的異常時,線程將終止。 spa
interrupt()方法只是請求終止線程,當調用此方法時,線程的中斷狀態將被置位。每一個線程都應該不時地檢查這個標誌,以判斷線程是否被中斷。 線程
當在一個被阻塞的線程(調用sleep或者wait)上調用interrupted方法時,阻塞調用將會被InterruptedException中斷。
it
沒有任何一個語言方面的需求要求一個被中斷的線程應該終止。中斷一個線程不過是爲了引發它的注意,被中斷的線程能夠決定如何響應中斷。某些線程是如此重要以致於應該處理完異常後繼續運行,而不是中斷。更是,更廣泛的狀況是,線程將簡單地將中斷做爲一個終止的請求。這種狀況下線程的run方法具備以下形式: io
public void run(){
try{
while(!Thread.currentThread().isInterrupted()&& more work to do){
do more work
}
}catch(InterruptedException e){
// thread was interrupted during sleep or wait
}finally{
cleanup,if required
}
//exiting the run method terminates the thread
} thread
若是在每次迭代以後都調用sleep方法(或者其它的可中斷方法),isInterrupted檢測就沒有用處也沒有必要。若是在中斷狀態被置位時調用sleep方法,它不會休眠。相反,它將清除這一狀態並拋出InterruptedException。所以,若是你的循環調用sleep,不要檢測中斷狀態,而是以下所示捕獲InterruptedException: require
public void run(){
try{
while(more work to do){
do more work
Thread.sleep(delay);
}
}catch (InterruptedException e){
//thread was interrupted during sleep or wait
}finally{
cleanup,if required
}
//exiting the run method terminates the thread
} 循環
有時候InterruptedException被抑制在很低的層次上,好比: 請求
void mySubTask(){
…
try{
sleep(dalay);
}catch(InterruptedException e){}
...
} 方法
這時候有一種更好的解決辦法:
void mySubTask(){
…
try{
sleep(dalay);
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
固然,最好的解決辦法是:
void mySubTask() throws InterruptedException{
…
sleep(dalay);
...
}