java线程操作中,会常用到interrupt这种中断处理,但是发现下层办法中断,上层方法依然感受不到线程处于中断,导致代码一直在执行,并没有停止,于是查看原理,发现下层方法里,虽然中断了,但是中断状态被下层的异常处理了,但是上层方法无法感知,故做此文记录
错误示例
public class RightWayInterruptThreadPro1 implements Runnable{
public void otherMethod() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true&&!Thread.currentThread().isInterrupted()){
System.out.println("go");
try {
otherMethod();
} catch (Exception e) {
e.printStackTrace();
System.out.println("插入日志");
}
}
}
public static void main(String[] args) {
Thread thread=new Thread(new RightWayInterruptThreadPro1());
thread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
效果如下,发现虽然下层方法已经中断,上次方法这里依然获取的线程中断状态为false,所以程序一直还在执行,并没有被上层捕获到异常状态信息,想做日志操作都不行
正确示例,通过让下层方法签名抛出异常的方法,能让上层方法捕获到打断异常,进行进行日志操作
public class RightWayInterruptThreadPro1 implements Runnable{
/**
* 利用方法签名的方式抛出异常,让上层方法得到此异常进行处理
* @throws InterruptedException
*/
public void otherMethod() throws InterruptedException{
Thread.sleep(1000);
}
@Override
public void run() {
while (true&&!Thread.currentThread().isInterrupted()){
System.out.println("go");
try {
otherMethod();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("插入日志");
}
}
}
public static void main(String[] args) {
Thread thread=new Thread(new RightWayInterruptThreadPro1());
thread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
效果图如下