Java线程中断疑问:移除break后为何仍会进入循环?
Java线程调用interrupt后仍进入循环的原因
先看移除break后的代码:
public static void main(String[] args) { Runnable r = () -> { while (!Thread.interrupted()) { System.out.println("Hola"); try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println("interrupted"); // 移除了break语句 } } }; Thread t = new Thread(r); t.start(); try { Thread.sleep(2000); } catch (InterruptedException ie) { ie.printStackTrace(); } t.interrupt(); }
核心原因:中断状态的自动重置与Thread.interrupted()的清除特性
这里的关键在于两个细节:
- 当
Thread.sleep()响应中断抛出InterruptedException时,JVM会自动将当前线程的中断标志重置为false,也就是说进入catch块时,线程已经处于「未中断」状态。 Thread.interrupted()是静态方法,它的作用是返回当前线程的中断状态,同时强制将中断标志重置为false(无论之前状态如何)。
具体执行流程
- 主线程等待2秒后调用
t.interrupt(),此时子线程正处于Thread.sleep(100)中,触发InterruptedException进入catch块。 - 执行完
System.out.println("interrupted")后,回到while循环的条件判断!Thread.interrupted():- 调用
Thread.interrupted(),此时线程的中断标志已经被JVM重置为false,所以返回false; !false结果为true,循环条件满足,线程继续进入循环打印"Hola"。
- 调用
对比:保留break的情况
如果catch块里有break,执行完打印后会直接跳出while循环,线程自然终止,不会继续后续的循环逻辑。
内容的提问来源于stack exchange,提问作者Marcos
相关产品推荐
相关产品推荐

