文章目录
恢复中断
- 恢复中断
- 屏蔽中断
当需要中断线程的时候, 最佳的方法, 还是如下文章提到的抛出异常,即传递中断. https://javaweixin6.blog.csdn.net/article/details/108091887
但是如果无法传递中断, 或者不想传递中断, 那么可以恢复中断.
恢复中断的代码示例:
public class RightWayStopThreadInProdReStop implements Runnable {
@Override
public void run() {
while (true) {
//在循环中, 判断线程是否已经被中断
if (Thread.currentThread().isInterrupted()) {
System.out.println("Interrupted 线程被中断, 程序运行结束 ");
break;
}
reInterrupt();
System.out.println("while循环中......");
}
}
private void reInterrupt() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
//捕获到中断异常后, 重新恢复中断
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new RightWayStopThreadInProdReStop());
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
}
其中的关键语句如下, 在子线程被中断的catch语句, 捕获后, 重新恢复中断. 并且在while循环中, 判断是否被中断. 程序运行如下 , 可以看到成功的中断了 .
把恢复中断的代码注释掉后, 可以看到中断失败. while循环一直在打印中.
什么叫做屏蔽中断 : 不在方法的签名中抛出异常, 也不catch语句中恢复中断,那么就感知不到线程的中断, 中断的信号就被屏蔽了