引入
蚂蚁金服面试题:如何停止、中断一个运行中的线程?

如果直接回答 interrupt 那就爆炸了💥,答案绝对是错误的,这就是对底层运行机制的不了解,所以我们首先要搞清楚这几个API的异同点
方法名 | 返回值 | 作用描述 |
interrupt | void | 一个实例方法,仅仅是将置标志符为true,不会停止线程 |
interrupted | boolean(静态方法) | 判断此线程是否被中断,并且清除当前中断状态,这个方法主要做了2件事: 1、返回当前线程的中断状态 2、将当前线程的中断状态设置为false *这个方法有点不好理解,因为连续调用2次的结果可能不一样 |
isInterrupted | boolean | 判断当前线程是否被中断(通过检测中断标识位置) |
中断协商机制
首先,一个线程不应该由其他线程来强制中断或者停止,而是应该由线程自己自行停止
所以,Thread.stop、Thread.suspend、Thread.resume 都已经废弃了
其次,在Java中没有办法立刻停止一条线程,然而停止线程却是很重要的,如取消一个耗时的操作。因此,Java提供了一种用于停止线程的机制--中断
中断协商机制并不是立刻+马上+now,stop一个线程
中断只是一种协商机制,Java并没有给中断增加任何语法,中断的过程完全是需要程序员自行实现。若需要中断一个线程,你需要手动调用该线程的Interrupt方法,该方法也仅仅是将线程对象中断的标识为设置为True;接着你需要自己写代码不断的检测当前线程的表示为,如果为True表示为中断,为false表示为未中断;
通过调用线程对象的interrupt方法将该线程的标识位置为true,可以在别的线程中调用,也可以在自己的线程中调用
中断Demo
volatile实现
通过volatile的可见性实现线程中断
AtomicBoolean实现
通过原子类进行实现
Thread类API实现
通过interrupt进行实现
package com.gzczy.concurrent.thread.interrupted;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @Description 停止线程三种方法
* @Author chenzhengyu
* @Date 2021-03-21 15:22
*/
public class STWThreadDemo {
private static volatile boolean flag = true;
private static AtomicBoolean atomicBoolean = new AtomicBoolean(true);
public static void main(String[] args) throws Exception{
Thread t1 = new Thread(() -> {
//demo1();
//demo2();
demo3();
},"t1");
t1.start();
TimeUnit.SECONDS.sleep(5);
new Thread(()->{
//flag = false;
//atomicBoolean.compareAndSet(true,false);
t1.interrupt();
}).start();
}
/**
* 第一种:使用volatile关键字进行停止
*/
public static void demo1(){
while (flag){
System.out.println("正在运行");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 第二种:通过原子类
*/
public static void demo2(){
while (atomicBoolean.get()){
System.out.println("正在运行");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 第三种:通过interrupt方法进行打断
*/
public static void demo3(){
while (!Thread.currentThread().isInterrupted()){
System.out.println("正在运行");
}
}
}
源码分析
具体来说,当对一个线程,调用interrupt()时
- 如果线程处于正常活跃的状态,那么将会该线程的中断标识设置为true,也就仅此而已,被设置中断标识的线程会继续运行,不受影响。所以调用调用interrupt()时,需要被调用的线程自己进行配合才行
- 如果线程处于阻塞状态(如图1代码所示)sleep、wait、join等状态,在别的线程中调用当前对象的interrupt()时,线程会立刻退出阻塞状态,并且抛出InterruptedException异常
生产案例
故障代码
在生产上,我们不能单纯的以为Interrupt能够中断线程,这只是一种协商机制,请看下面案例
package com.gzczy.concurrent.thread.interrupted;
import java.util.concurrent.TimeUnit;
/**
* @Description 线程中断demo
* @Author chenzhengyu
* @Date 2021-03-21 15:49
*/
public class InterruptErrorDemo {
public static void main(String[] args) throws Exception{
Thread t1 = new Thread(() -> {
CanNotStop();
}, "t1");
t1.start();
TimeUnit.SECONDS.sleep(3);
Thread t2 = new Thread(()->{
t1.interrupt();
},"t2");
t2.start();
}
/**
* 抛出异常后仍然 无法正常打断
*/
public static void CanNotStop(){
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Running.....");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
运行结果
Running.....
Running.....
Running.....
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:340)
at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
at com.gzczy.concurrent.thread.interrupted.InterruptErrorDemo.CanNotStop(InterruptErrorDemo.java:31)
at com.gzczy.concurrent.thread.interrupted.InterruptErrorDemo.lambda$main$0(InterruptErrorDemo.java:14)
at java.lang.Thread.run(Thread.java:748)
Running.....
Running.....
Running.....
Running.....
通过运行结果我们可以观察到,运行完成就抛出了异常,然后就一直停不下来了。这种情况会导致在生产实际情况下的系统卡顿,因为程序无法正常终止。在代码中,我们翻开interrupt源码可以发现这句话:当我们打断正在睡眠的线程时候,我们会清除打断标记,由于t2刚刚是发起了打断请求,设置打断标识为true,但是因为有睡眠代码块,打断时候会把打断标识清空,导致无法进入break代码块,即便是异常也没有停,所以我们需要将线程中断标记位置改为true
正确代码
我们在刚刚catch代码块再次打断,复位标志位,使其能够正确的中断线程
package com.gzczy.concurrent.thread.interrupted;
import java.util.concurrent.TimeUnit;
/**
* @Description 线程中断demo
* @Author chenzhengyu
* @Date 2021-03-21 15:49
*/
public class InterruptErrorDemo {
public static void main(String[] args) throws Exception{
Thread t1 = new Thread(() -> {
CanNotStop();
}, "t1");
t1.start();
TimeUnit.SECONDS.sleep(3);
Thread t2 = new Thread(()->{
t1.interrupt();
},"t2");
t2.start();
}
/**
* 抛出异常后仍然 无法正常打断(原因请点击进入API查看,sleep wait join方法打断会清除打断标识)
* 在异常部分需要再次打断 重置标志位
*/
public static void CanNotStop(){
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Running.....");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
//我们在刚刚catch代码块再次打断,复位标志位,使其能够正确的中断线程
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
}
方法加深理解
判断下列代码输出的结果
package com.gzczy.concurrent.thread.interrupted;
import lombok.extern.slf4j.Slf4j;
/**
* @Description 对比打断方法中间
* @Author chenzhengyu
* @Date 2021-03-21 16:14
*/
@Slf4j(topic = "c.InterruptCompare")
public class InterruptCompare {
public static void main(String[] args) {
log.info("==>"+Thread.interrupted());
log.info("==>"+Thread.interrupted());
log.info("========================");
Thread.currentThread().interrupt();
log.info("========================");
//通过观察结果 我们可以看到这里显示为true 因为刚刚打断了,与此同时会将打断状态清空,下次判断为false
log.info("==>"+Thread.interrupted());
// 此方法并不会重置标识位置,只是单纯的显示一下当前状态
log.info("==>"+Thread.currentThread().isInterrupted());
log.info("==>"+Thread.interrupted());
}
}
结果
16:47:54.803 [main] c.InterruptCompare - ==>false
16:47:54.806 [main] c.InterruptCompare - ==>false
16:47:54.806 [main] c.InterruptCompare - ========================
16:47:54.806 [main] c.InterruptCompare - ========================
16:47:54.806 [main] c.InterruptCompare - ==>true
16:47:54.806 [main] c.InterruptCompare - ==>false
16:47:54.806 [main] c.InterruptCompare - ==>false
底层源码分析
log.info("==>"+Thread.interrupted());
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
log.info("==>"+Thread.currentThread().isInterrupted());
public boolean isInterrupted() {
return isInterrupted(false);
}
通过方法观察我们可以看到清晰的表达了”中断状态将会传入的ClearInterrupted参数值确定是否需要重置“
由此可以得出结论:
静态方法Interrupted将会清除中断状态(传入参数的ClearInterrupted为true)
实例方法isInterrupted则不会(传入参数的ClearInterrupted为false)