线程中断机制
从阿里蚂蚁金服面试题讲起
Java.lang.Thread类下面的这三个方法怎么用,用在哪,使用这些方法的利弊如何?
- 如何中断一个运行中的线程?
- 如何停止一个运行中的线程?
什么是中断机制
- 一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止,自己来决定自己的命运,所以,
Thread.stop
、Thread.suspend
、Thread.resume
都已经被废弃了
- 在Java中没有办法立即停止一条线程,然而停止线程却尤为重要,如取消一个耗时操作。因此,Java提供了一种用于停止线程的协商机制(中断标识协商机制)来中断(并非强制中断,如无烟餐厅的服务员通过协商让顾客停止抽烟,而不是直接将烟拿走)
- 中断只是一种协作协商机制,Java没有给中断提供任何语法,中断的过程完全需要程序员自行实现。若要中断一个线程,需要手动调用该线程的interrupt方法,该方法也仅仅是将该线程对象的中断标识设置为true,接着需要自己写代码不断检测当前线程的标识位,如果为true,表示别的线程请求这条线程中断,此时究竟应该做什么需要自己写代码实现。
- 每个线程对象都有一个中断标识位,用于表示线程是否被中断;该标识位为true表示中断,为false表示未中断;通过调用线程对象的interrupt方法将该线程的标识位设置为true。interrupt方法可以在别的线程中调用,也可以在自己的线程中调用。
中断的相关API方法之三大方法
interrupt()
public void interrupt()
:实例方法,仅仅是设置线程的中断状态为true,发起一个协商而不会立刻停止线程
Thread.interrupted()
public static boolean interrupted()
- 静态方法
Thread.interrupted();
- 判断线程是否被中断并清除当前中断状态(做了两件事情)
- 1、返回当前线程的中断状态(布尔值),测试当前线程是否已被中断
- 2、将当前线程的中断状态重新设置为false
- 如果连续两次调用此方法,连续调用两次的结果可能不一样,第二次肯定返回false(无论第一次是什么,最后都是将中断状态设置为false)
- 静态方法
isInterrupted()
public boolean isInterrupted()
- 实例方法,通过检查中断标志位判断当前线程是否被中断
Thread.interrupted()和isInterrupted()的区别
- 两者调用的native方法是一样的
- 静态方法interrupted将会清除中断状态(传入的参数ClearInterrupted为true)
- 实例方法isInterrupted则不会(传入的参数ClearInterrupted为false)
如何停止中断运行中的线程
通过一个volatile变量实现
volatile表示的变量在高并发时具有可见性:如果线程t1、t2都共用一个volatile变量,t2修改了变量的状态,t1也可以看到
/**
使用volatile修饰一个标识符来决定是否结束线程
*/
public class InterruptDemo {
// volatile表示的变量在高并发时具有可见性
static volatile boolean isStop = false;
public static void main(String[] args) {
new Thread(() -> {
while (true) {
if (isStop) {
System.out.println(Thread.currentThread().getName() + " isStop的值被改为true,t1程序停止");
break;
}
System.out.println("t1-----------hello volatile");
}
}, "t1").start();
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
isStop = true;
}, "t2").start();
}
}
【输出】
t1-----------hello volatile
t1-----------hello volatile
t1-----------hello volatile
t1-----------hello volatile
t1-----------hello volatile
t1-----------hello volatile
t1 isStop的值被改为true,t1程序停止
通过原子布尔型AutomicBoolean
/**
使用AtomicBoolean,原子布尔
*/
public class InterruptDemo {
static AtomicBoolean atomicBoolean = new AtomicBoolean(false);
public static void main(String[] args) {
new Thread(() -> {
while (true) {
if (atomicBoolean.get()) {
System.out.println(Thread.currentThread().getName() + " atomicBoolean的值被改为true,t1程序停止");
break;
}
System.out.println("t1-----------hello atomicBoolean");
}
}, "t1").start();
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
atomicBoolean.set(true);
}, "t2").start();
}
}
【输出】
t1-----------hello atomicBoolean
t1-----------hello atomicBoolean
t1-----------hello atomicBoolean
t1-----------hello atomicBoolean
t1-----------hello atomicBoolean
t1 atomicBoolean的值被改为true,t1程序停止
通过Thread类自带的中断API实例方法实现
- 在需要中断的线程中不断监听中断状态,一旦发生中断,就执行相应的中断处理业务逻辑来停止线程
- 线程的默认中断状态是false
/**
使用interrupt() 和isInterrupted()来中断某个线程
*/
public class InterruptDemo {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (true) {
// Thread.currentThread():获得t1
if (Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName() + " isInterrupted()的值被改为true,t1程序停止");
break;
}
System.out.println("t1 -----------hello isInterrupted()");
}
}, "t1");
t1.start();
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// t2向t1发起协商,将t1中的中断标识位设为true,希望t1可以停下来
new Thread(() -> t1.interrupt(), "t2").start();
// 也可以由t1自行设置
t1.interrupt();
}
}
【输出】
t1 -----------hello isInterrupted()
t1 -----------hello isInterrupted()
t1 -----------hello isInterrupted()
t1 -----------hello isInterrupted()
t1 isInterrupted()的值被改为true,t1程序停止
源码分析
interrupt
- 当前线程的中断标识为true,是不是线程就立刻停止?答案是不立刻停止,当对一个线程调用interrupt时:
- 如果线程处于正常活动状态,那么会将该线程的中断标志设置为true,仅此而已,被设置中断标志的线程将继续正常运行,不受影响,所以interrupt()并不能真正的中断线程,需要被调用的线程自己进行配合才行
- 如果线程t1处于阻塞状态(例如调用wait(), wait(Long), wait(Long,int), join(), join(Long), join(long,int), sleep(long), sleep(Long,int)),在别的线程t2中调用当前线程对象的interrupt方法,那么线程t1将立即退出被阻塞状态(interrupt状态也将被清除,即设置为false),并抛出一个InterruptedException异常
- 使用interrupt中断不活动的线程不会产生任何影响,因此对不活动的线程调用interrupt没有什么意义
isInterrupted
boolean:是否重置标志位
三大方法测试
测试interrupt()是否会让线程立刻中断:
- 如果可以中断,输出不到300
运行结果:
程序继续运行到300,且当t1的程序运行完之后,中断标志位为false,表示没有任何影响
结论:
- 执行interrupt方法将t1标志位设置为true后,t1没有中断,仍然完成了任务后再结束
- 在2000毫秒后,t1已经结束称为不活动线程,设置状态为没有任何影响
public class InterruptDemo2 {
public static void main(String[] args) {
// 实例方法interrupt()仅仅是设置线程的中断状态位为true,不会停止线程
Thread t1 = new Thread(() -> {
for (int i = 1; i <= 300; i++) {
System.out.println("------: " + i);
}
/**
* ------: 298
* ------: 299
* ------: 300
* t1线程调用interrupt()后的中断标志位02:true
*/
System.out.println("t1线程调用interrupt()后的中断标志位02:" + Thread.currentThread().isInterrupted());
}, "t1");
t1.start();
System.out.println("t1线程默认的中断标志位:" + t1.isInterrupted());//false
// 2毫秒之后,使用interrupt
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.interrupt();//true
/**
* ------: 130
* ------: 131
* ------: 132
* t1线程调用interrupt()后的中断标志位01:true
*/
System.out.println("t1线程调用interrupt()后的中断标志位01:" + t1.isInterrupted());//true
try {
TimeUnit.MILLISECONDS.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 2000毫秒后,t1线程已经不活动了,中断标识是什么?
System.out.println("t1线程调用interrupt()后的中断标志位03:" + t1.isInterrupted());//false
}
}
对阻塞的线程调用interrupt()
public class InterruptDemo3 {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName() + " 中断标志位为:" + Thread.currentThread().isInterrupted() + " 程序停止");
break;
}
// sleep方法抛出InterruptedException后,中断标识也被清空置为false,如果没有在
// catch方法中调用interrupt方法再次将中断标识置为true,这将导致无限循环了
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// Thread.currentThread().interrupt();
e.printStackTrace();
}
System.out.println("-------------hello InterruptDemo3");
}
}, "t1");
t1.start();
// 1秒之后,t2执行
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
t1.interrupt();
}, "t2").start();
}
}
【运行】
- t1正在sleep,然后t2调用t1的interrupt,这时t1会报异常,且会将中断标志位清除,程序永远停不下来,导致死循环
【解决方案】
- 在catch块中,再次调用interrupt()方法将中断标志位设置为true
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
【总结】
1、中断标志位默认为false 2、t2对t1发出 t1.interrupt();
- 中断标志位为true:正常情况,程序停止
- 中断标志位为true:异常情况,发生InterruptedException ,将会把中断状态清除,中断标志位为false,导致死循环
3、需要在catch块中,再次调用interrupt()方法将中断标志位设置为true
静态方法Thread.interrupted()
public class InterruptDemo4 {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + "\t" + Thread.interrupted());//false
System.out.println(Thread.currentThread().getName() + "\t" + Thread.interrupted());//false
System.out.println("-----------1");
Thread.currentThread().interrupt();
System.out.println("-----------2");
System.out.println(Thread.currentThread().getName() + "\t" + Thread.interrupted());//true
System.out.println(Thread.currentThread().getName() + "\t" + Thread.interrupted());//false
}
}
【输出】
main false
main false
-----------1
-----------2
main true
main false
总结
- public void interrupt() 是一个实例方法,它通知目标线程中断,也仅仅是设置目标线程的中断标志位为true
- public boolean isInterrupted() 是一个实例方法,它判断当前线程是否被中断(通过检查中断标志位)并获取中断标志
- public static boolean interrupted() 是一个静态方法,返回当前线程的中断真实状态(boolean类型)后会将当前线程的中断状态设为false
文章说明
该文章是本人学习 尚硅谷 的学习笔记,文章中大部分内容来源于 尚硅谷 的视频尚硅谷JUC并发编程(对标阿里P6-P7),也有部分内容来自于自己的思考,发布文章是想帮助其他学习的人更方便地整理自己的笔记或者直接通过文章学习相关知识,如有侵权请联系删除,最后对 尚硅谷 的优质课程表示感谢。