为何第二个InterruptedException处理示例优于第一个?求解析
两段InterruptedException处理代码的差异分析
先看两段代码的实现:
第一段代码:
public void run() { while (. . .) { . . . try { . . . Thread.sleep(delay); . . . } catch (InterruptedException exception) {} . . . } } }
第二段代码:
public void run() { try { while (. . .) { . . . Thread.sleep(delay); . . . } } catch (InterruptedException exception) { . . . } }
为什么第一段代码不会终止线程?
- 第一段把
try-catch放在while循环内部,当线程被中断时,Thread.sleep()会抛出InterruptedException,但catch块直接吞掉了异常,没有做任何处理。 - 更关键的是:JVM抛出
InterruptedException时,会自动清除当前线程的中断标志位。这意味着线程本身不知道自己被中断过,循环条件也没被修改,所以异常处理完后,线程会继续执行下一轮while循环,完全无视中断请求。
第二段代码的优势在哪里?
- 第二段把
try-catch放在while循环外面,当Thread.sleep()抛出InterruptedException时,会直接跳出整个while循环,进入catch块处理异常(比如记录日志、清理资源),之后run()方法执行完毕,线程自然终止。 - 这种写法正确响应了线程中断的设计意图:中断是请求线程停止执行的信号,代码应该在收到信号后合理收尾并终止线程,而非无视它。
补充:如果某些场景下不能直接终止线程,也不该吞掉InterruptedException,而是要通过Thread.currentThread().interrupt()重新设置中断标志位,让上层代码能感知到中断请求。
内容的提问来源于stack exchange,提问作者wydra__
相关产品推荐
相关产品推荐

