为什么需要中断
在线程执行过程中,有很多场景需要终止线程的运行。这时就需要一个方法来结束线程并返回结果。
中断的方法
Thread类中提供了3个有关中断的方法:
interrupt():设置中断标志位为true
interrupted();检测中断标志,如果有设置会清除标志位
isInterrupted():检测中断标志位
使用场景
- 大家都用过迅雷下载电影,假如一个电影下载到一半,可能是网速太慢了,导致你不想下了,你会删除这个任务。就需要中断这个下载线程。
- 网上的一些刷票软件,可能会开启多线程去帮你抢票,一旦抢到了就会中断其它线程。
代码演示
public class InterruptTest {
public static void main(String[] args) {
Thread thread = new Thread (){
@Override
public void run() {
while(true){
if (Thread.currentThread().isInterrupted()){
System.out.println("中断线程");
}else {
System.out.println("还在运行中");
}
}
}
};
thread.start();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
截取了一部分结果
程序还一直会运行下去,可以看出并不是真正结束了运行,只是设置了中断标示,可以让程序猿自行处理。
比如加一行代码,随便抛一个异常就能结束线程运行了
if (Thread.currentThread().isInterrupted()){
System.out.println("中断线程");
throw new NumberFormatException();
}
线程在阻塞状态下调用中断方法会抛出interruptException,所以调用阻塞方法的线程必须捕获该异常如(sleep,wait,join)
上面代码修改一下
public class InterruptTest {
public static void main(String[] args) {
Thread thread = new Thread (){
@Override
public void run() {
while(true){
try {
System.out.println("开始休眠线程");
Thread.sleep(1000);
System.out.println("线程休眠结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
为什么不推荐使用stop()
Thread类中还有一个stop()方法,已经被废弃了
为什么废弃它,是因为在多线程环境下,其中一个线程调用stop方法会释放线程调用对象上的所有锁,如果该对象还在被其他线程调用,会产生数据不一致的问题。