- interrupt() 是給線程設置中斷標誌,線程仍會繼續運行
- interrupted() 是檢測中斷並清除中斷狀態,第二次再調用時中斷狀態已被清除,將返回一個 false
- isInterrupted() 只檢測中斷,不清除中斷狀態
interrupted() 作用於當前線程(主線程)
,interrupt(),isInterrupted() 作用於此線程,即代碼中調用此方法的實例所代表的線程
public class InterruptTest {
public static void main(String[] args) {
MyThread1 thread = new MyThread1();
thread.start();
thread.interrupt();
System.out.println("第一次調用thread.isInterrupted():"+thread.isInterrupted());
System.out.println("第二次調用thread.isInterrupted():"+thread.isInterrupted());
//測試interrupted()函數
System.out.println("第一次調用thread.interrupted():"+thread.interrupted());
System.out.println("第二次調用thread.interrupted():"+thread.interrupted());
System.out.println("thread是否存活:"+thread.isAlive());
}
}
class MyThread1 extends Thread{
public void run(){
for(int i=0;i<10;i++){
System.out.println("i="+(i+1));
}
}
}
輸出結果:
第一次調用thread.isInterrupted():true
第二次調用thread.isInterrupted():true
第一次調用thread.interrupted():false
第二次調用thread.interrupted():false
thread是否存活:true
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i=10
從輸出結果看,可能會有疑惑,爲什麼後面兩個interrupted方法輸出的都是false,而不是預料中的一個true一個false
interrupted() 方法測試的是當前線程是否被中斷,當前線程
!!!這裏當前線程是 main線程,而thread.interrupt()中斷的是thread線程,這裏的此線程就是thread線程,所以當前線程main從未被中斷過
儘管interrupted()方法是以thread.interrupted()的形式被調用,但它檢測的仍然是main線程而不是檢測thread線程,所以thread.interrupted() 在這裏相當於 main.interrupted()
。
對於這點,下面我們修改進行測試
Thread.currentThread()函數可以獲取當前線程,下面代碼中獲取的是main線程
public class InterruptTest {
public static void main(String[] args ) throws InterruptedException {
Thread.currentThread().interrupt();
System.out.println("第一次調用Thread.currentThread().interrupt():"+Thread.currentThread().isInterrupted());
System.out.println("第一次調用thread.interrupted():"+Thread.currentThread().interrupted());
System.out.println("第二次調用thread.interrupted():"+Thread.currentThread().interrupted());
}
}
這裏都是針對當前線程在操作,如果 interrupted() 方法有檢測中斷並清除中斷狀態的作用,預料中的輸出應該是true-true-false,實際輸出如下:
第一次調用 Thread.currentThread().interrupt():true
第一次調用 thread.interrupted(): true
第二次調用 thread.interrupted(): false
結果證明猜想是正確的
若果想要是實現調用 interrupt()方法 真正的終止線程,則可以在線程的 run()方法中做處理即可,比如直接跳出 run()方法 使線程結束,視具體情況而定,下面是一個例子
public class MyThread extends Thread {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("i="+(i+1));
if(this.isInterrupted()){
System.out.println("通過this.isInterrupted()檢測到中斷");
System.out.println("第一個interrupted()"+this.interrupted());
System.out.println("第二個interrupted()"+this.interrupted());
break;
}
}
System.out.println("因爲檢測到中斷,所以跳出循環,線程到這裏結束,因爲後面沒有內容了");
}
}
測試MyThread
public class InterruptTest {
public static void main(String[] args ) throws InterruptedException {
MyThread myThread=new MyThread();
myThread.start();
myThread.interrupt();
//sleep等待一秒,等myThread運行完
Thread.currentThread().sleep(1000);
System.out.println("myThread線程是否存活:"+myThread.isAlive());
}
}
輸出結果:
i=1
通過 this.isInterrupt()檢測到中斷
第一個 interrupt() true
第二個 interrupt() false
因爲檢測到中斷,所以跳出循環,線程到這裏結束,因爲後面沒有內容了
myThread 線程是否存活:false