涉及到线程停止的问题

涉及到线程挺停止的时候的问题

private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new RuntimeException(THREAD_NAME + "收到中断异常!", e);
        }
    }

代码报错是这样的:

InterruptedExceptions should never be ignored in the code, and simply logging the exception counts in this case as “ignoring”. The throwing of the InterruptedException clears the interrupted state of the Thread, so if the exception is not handled properly the fact that the thread was interrupted will be lost. Instead, InterruptedExceptions should either be rethrown - immediately or after cleaning up the method’s state - or the thread should be re-interrupted by calling Thread.interrupt() even if this is supposed to be a single-threaded application. Any other course of action risks delaying thread shutdown and loses the information that the thread was interrupted - probably without finishing its task.

翻译如下:

代码中决不能忽略InterruptedExceptions,只需将异常计数记录为“忽略”。抛出InterruptedException将清除线程的中断状态,因此,如果异常处理不当,线程被中断的事实将丢失。相反,InterruptedExceptions应该立即或在清理方法状态之后被重新thrown,或者应该通过调用来重新中断线程线程中断()即使这应该是一个单线程应用程序。任何其他操作都有可能延迟线程关闭,并丢失线程被中断的信息—可能还没有完成任务。

意思就是说在抛出异常之前,将现在的线程重新中断。如下:

private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(THREAD_NAME + "收到中断异常!", e);
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值