涉及到线程挺停止的时候的问题
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);
}
}