如何停止线程
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方法停止该线程时会把锁释放掉,可能造成数据不一致的情况。