停止线程的正确方法

原理解释:使用interrupt来通知,而不是强制(普通情况下停止线程)

while内try/catch的问题 中断被清除 sleep的设计理念,会把interrupt的标记位给清除

1.优先选择:传递中断

/**
 * 最佳实践:catch了InterruptedExcetion之后的优先选择,在方法签名中抛出异常
 * try catch在内 已经把异常给吞了,while这里检测不到异常 所以要把异常返回回去
 *
 */
public class RightWayStopThreadInProd implements Runnable{
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadInProd());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }

    @Override
    public void run() {
        //run方法抛出exception
        while (true && !Thread.currentThread().isInterrupted()){
            System.out.println("go");
            try {
                throwInMethod();
            } catch (InterruptedException e) {
                System.out.println("保存日志");
                e.printStackTrace();
            }
        }
    }
    /**
     * 在休眠过程中 去中断
     * 在签名中实现
     * @throws InterruptedException
     */
    private void throwInMethod() throws InterruptedException {
        Thread.sleep(1000);
        /*try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }
}

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

如果不能抛出中断。要如何做?

如果不想或无法传递InterruptedException(例如用run方法的时候,就不让该方法Throws InterruptedException),那么应该选择在catch子句中调用Thread.currentThread().interrupt()来恢复设置中断状态,以便于在后续的执行中依然能够检查到刚才发生了中断。

3.不应屏蔽中断

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值