You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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(无论之前状态如何)。

具体执行流程

  1. 主线程等待2秒后调用t.interrupt(),此时子线程正处于Thread.sleep(100)中,触发InterruptedException进入catch块。
  2. 执行完System.out.println("interrupted")后,回到while循环的条件判断!Thread.interrupted():
    • 调用Thread.interrupted(),此时线程的中断标志已经被JVM重置为false,所以返回false;
    • !false结果为true,循环条件满足,线程继续进入循环打印"Hola"。

对比:保留break的情况

如果catch块里有break,执行完打印后会直接跳出while循环,线程自然终止,不会继续后续的循环逻辑。

内容的提问来源于stack exchange,提问作者Marcos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:00:47