您当前的位置: 首页 >  Java

java持续实践

暂无认证

  • 0浏览

    0关注

    746博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java多线程 中断线程最优方法之 恢复中断

java持续实践 发布时间:2020-08-26 21:03:52 ,浏览量:0

文章目录
      • 恢复中断
      • 屏蔽中断

恢复中断

当需要中断线程的时候, 最佳的方法, 还是如下文章提到的抛出异常,即传递中断. 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语句中恢复中断,那么就感知不到线程的中断, 中断的信号就被屏蔽了

关注
打赏
1658054974
查看更多评论
立即登录/注册

微信扫码登录

0.0664s