正确停止线程

原理介绍:使用interrupt来通知,而不是强制

核心:想要停止线程其实是如何运用interrupt来通知那个线程,以及被停止的线程如何配合。

我们作为想停止线程的一方,根本没有能力去强行停止。由于我们想要终端的是其他的线程,这个线程很有可能不是我们来写的,我们或许对这个正在运行的线程的业务逻辑根本就不熟悉,我们想让它停止,其实是希望他完成了一系列的保存、交接工作再停止,而不希望它立刻停止,使它陷入一种混乱的状态。被停止的线程本身,对于自己的业务逻辑是最熟悉的, 所以在设计的时候把停止的权利和步骤交给了被停止线程本身。这个就是一个设计的出发点。

正确的停止方法:interrupt

1、线程通常会在什么情况下停止呢?

当run方法中的所有代码都执行完毕。线程中有异常出现,但是没有捕获。

2、线程可能被阻塞

3、如果线程在每次迭代后都阻塞

4、如果while里面放try/catch,会导致中断失效

package threadcoreknowledge.stopthreads;

/**
 * 描述:     如果while里面放try/catch,会导致中断失效
 */
public class CantInterrupt {

    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            int num = 0;
            while (num <= 10000 && !Thread.currentThread().isInterrupted()) {
                if (num % 100 == 0) {
                    System.out.println(num + "是100的倍数");
                }
                num++;
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(5000);
        thread.interrupt();
    }
}

原因

虽然我们利用了!Thread.currentThread().isInterrupted()来检查是不是已经中断,但是好像毫无效果。之所以会产生这样的原因, 是因为java在这几sleep函数的时候,有这样的一个理念,一旦响应了中断 ,于是就会把线程的这个interrupt标记清除。也就是说在刚才的情况下,由于interrupt标记被清除,所以检查不到任何别中断的迹象,导致程序不能退出。

实际开发中两种最佳实践

优先选择传递中断
1、catch了InterruptedExcetion之后的优先选择:在方法签名中抛出异常 那么在run()就会强制try/catch

package threadcoreknowledge.stopthreads;

import threadcoreknowledge.createthreads.ThreadStyle;

/**
 * 描述:     最佳实践:catch了InterruptedExcetion之后的优先选择:在方法签名中抛出异常 那么在run()就会强制try/catch
 */
public class RightWayStopThreadInProd implements Runnable {

    @Override
    public void run() {
        while (true && !Thread.currentThread().isInterrupted()) {
            System.out.println("go");
            try {
                throwInMethod();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                //保存日志、停止程序
                System.out.println("保存日志");
                e.printStackTrace();
            }
        }
    }

    private void throwInMethod() throws InterruptedException {
            Thread.sleep(2000);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadInProd());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}

不想或者无法传递:恢复中断

2、在catch子语句中调用Thread.currentThread().interrupt()来恢复设置中断状态,以便于在后续的执行中,依然能够检查到刚才发生了中断。回到刚才RightWayStopThreadInProd补上中断,让它跳出。

package threadcoreknowledge.stopthreads;

/**
 * 描述:最佳实践2:在catch子语句中调用Thread.currentThread().interrupt()来恢复设置中断状态,以便于在后续的执行中,依然能够检查到刚才发生了中断
 * 回到刚才RightWayStopThreadInProd补上中断,让它跳出
 */
public class RightWayStopThreadInProd2 implements Runnable {

    @Override
    public void run() {
        while (true) {
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("Interrupted,程序运行结束");
                break;
            }
            reInterrupt();
        }
    }

    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 RightWayStopThreadInProd2());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
} 

不应该屏蔽中断

响应中断的方法总结列表。

在这里插入图片描述在这里插入图片描述

总结:为什么使用interrupt来停止线程,有什么好处?

被中断的线程拥有如何响应中断的权利,因为有些线程的某些代码是非常重要的,我们必须要得等待这些线程处理完之后,或者他们准备好之后,再由他们主动去终止,或者如果他们不想理会我们的中断,这也是非常ok的。我们不应该鲁莽的使用stop方法,而是使用interrupt方法发出一个信号,让他们自己去处理。 这样线程更加安全,数据的一致性也得到了保证。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值