Java中interrupt() interrupted() isInterrupted()辨析:
- interrupt()是將線程的中斷標記設置爲true,但不會停止線程。在中斷狀態下如果線程處於阻塞狀態(即調用了sleep(),wait(),join()方法)就會產生一個InterruptedException,並且由於線程處於阻塞狀態,所以該中斷標記立即清除爲false
- interrupted()是測試當前線程是否處於中斷狀態,是返回true,並且調用後會立即將該中斷標記清除爲false
public static boolean interrupted() {
return currentThread().isInterrupted(true);//其中本地方法isInterrupted()中參數true表示是否清除狀態位
}
private native boolean isInterrupted( boolean ClearInterrupted);
- isInterrupted()是作用於調用該方法的線程對象所對應的線程(線程對象對應的線程不一定是當前運行的線程),調用後不會清除中斷標記
public boolean isInterrupted() {
return isInterrupted(false);
}
具體實例:
- 阻塞過後,中斷標記的清除:
public class TestInterrupt {
public static void main(String[] args) {
System.out.println("主線程開始。。");
Thread.currentThread().interrupt();
try {
Thread.sleep(1000);//會拋出異常
} catch (InterruptedException e) {
System.err.println("sleep方法出現了異常");
}
//線程阻塞後,中斷狀態被清除爲false
System.out.println("主線程是否處於中斷狀態:" + Thread.currentThread().isInterrupted());//false
System.out.println("主線程結束。。");
}
}
/*
結果:
主線程開始。。
sleep方法出現了異常
主線程是否處於中斷狀態:false
主線程結束。。
*/
- 使用isInterrupt(),不會清除中斷標記:
public class TestIsInterrupt {
public static void main(String[] args) {
System.out.println("主線程開始。。");
Thread.currentThread().interrupt();
System.out.println("主線程是否處於中斷狀態:" + Thread.currentThread().isInterrupted());//true
System.out.println("主線程是否處於中斷狀態:" + Thread.currentThread().isInterrupted());//true
System.out.println("主線程結束。。");
}
}
/*
結果:
主線程開始。。
主線程是否處於中斷狀態:true
主線程是否處於中斷狀態:true
主線程結束。。
*/
- 使用interrupt(),會清除中斷標記:
public class TestInterrupt {
public static void main(String[] args) {
System.out.println("主線程開始。。");
Thread.currentThread().interrupt();
System.out.println("主線程是否處於中斷狀態:" + Thread.interrupted());//true
System.out.println("主線程是否處於中斷狀態:" + Thread.interrupted());//false
System.out.println("主線程結束。。");
}
}
/*
結果:
主線程開始。。
主線程是否處於中斷狀態:true
主線程是否處於中斷狀態:false
主線程結束。。
*/