如何中止線程
JDK API推薦使用中止線程的方法Thread.interrupt()方法
- 既然不能直接stop線程,那麼只有一種方法能夠讓線程結束,那就是讓run方法運結束。Thread.interrupt()表明的意思是「中止,停止」。可是這個方法須要加入一個判斷才能夠完成線程的中止。一旦檢測到線程處於中斷狀態,那麼就有機會結束run方法。
package com.bingo.thread.stopThread;
/**
* Created with IntelliJ IDEA.
* Description: 中止線程不推薦使用stop方法,此方法不安全,咱們能夠使用Thread.interrupt()
* User: bingo
*/
public class Run {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
myThread.interrupt();
System.out.println("end...");
}
}
class MyThread extends Thread{
@Override
public void run() {
super.run();
for (int i = 0; i < 10000 ; i++) {
if(this.isInterrupted()){
System.out.println("已是中止狀態了,我要退出了");
break;
}
System.out.println("i="+(i+1));
}
}
}
//運行結果
i=1
......
i=3102
i=3103
i=3104
i=3105
i=3106
i=3107
i=3108
end...
已是中止狀態了,我要退出了
- interrupt能夠清除線程的凍結狀態,讓線程恢復到可運行的狀態上來
package com.bingo.thread.stopThread;
/**
* Created with IntelliJ IDEA.
* Description: interrupt能夠清除線程的凍結狀態,讓線程恢復到可運行的狀態上來。
* User: bingo
*/
public class Run2 {
public static void main(String[] args) {
MyThread2 thread = new MyThread2();
thread.start();
thread.interrupt();
System.out.println("main end...");
}
}
class MyThread2 extends Thread{
@Override
public void run() {
System.out.println("run begin...");
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
System.out.println("run 在沉睡中被停止,進入catch");
e.printStackTrace();
}
System.out.println("run end...");
}
}
//運行結果:
main end...
run begin...
run 在沉睡中被停止,進入catch
run end...
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.bingo.thread.stopThread.MyThread2.run(Run2.java:26)
- 從運行結果咱們能夠看到,原本run方法睡眠時間爲1000秒,可是打印結果倒是瞬間的,其實sleep已經被interrupt方法給打斷,此時線程凍結狀態被清除,並拋出異常,被catch捕獲,打印異常信息。
暴力中止——Stop
- 若是某個線程加鎖,stop方法中止該線程時會把鎖釋放掉,可能形成數據不一致的狀況。