最近项目中开起来sonar的规范扫描, 提示了InterruptedException处理有问题, 所以记录下
当前的做法:
方式A: 什么都不做, 或者 打印异常的堆栈信息, 或者 记录log
==============================================
单线程场景下是不会抛该异常的
==============================================
假设有A,B 共2个线程, B线程希望A停下来
A线程在等待锁/睡眠时, 根据自身的业务来决定, 是真的停下来, 还是忽略异常 继续执行
InterruptedException就是这个信号
1.在使用Future类的get方法时是必须处理InterruptedException, 所以可以看看业务设计上有没有被其他线程中断的逻辑,
如果没有 那直接使用Thread.currentThread().interrupt(); sonar就不会标红
或者打印异常的堆栈信息, 记录log等
如果有, 则看看当前业务的重要性, 不重要的同上;
重要的业务, 肯定是要做业务表failure状态的更新, 给上下游发通知, 资源释放等操作
(代码层面就是 把异常向上抛, 或者catch内处理 资源释放等操作)
===============================================
如果只打印log
因为InterruptedException异常会清除 中断状态, 所以线程任然会继续执行
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Thread is running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread is interrupted.");
}
}
});
所以要重新设置中断标记 Thread.currentThread().interrupt();
当while的条件是true 死循环时, 要记得加上return
public class InterruptExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
while (true) {
System.out.println("Thread is running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread is interrupted.");
Thread.currentThread().interrupt();
return;
}
}
});
thread.start();
// 主线程等待一段时间后中断子线程
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}