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

Java多线程如何使用interrupt方法正确终止自定义StopThread线程

问题根因

你代码的核心问题是:Thread.sleep()方法抛出InterruptedException的时候,会自动清除线程的中断状态标记,所以catch块执行完之后,while (!Thread.interrupted())判断拿到的还是false,循环就会继续执行,无法正常退出。

可行修改方案

你不需要自定义布尔标志位,只需要在捕获中断异常后做简单调整即可,有两种符合要求的实现方式:

  • 方案1:捕获异常后手动重置中断状态,在catch块内调用Thread.currentThread().interrupt()重新给当前线程打上中断标记,下一轮循环判断时就能检测到中断信号正常退出
  • 方案2:捕获异常后直接break跳出while循环,收到中断信号的目标就是终止线程,直接跳出也完全符合逻辑

修改后示例代码(方案1实现)

class StopThread extends Thread {
    @Override
    public void run() {
        while (!Thread.interrupted()) {
            System.out.println("Thread is running....");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                // 手动重新设置中断标志位
                Thread.currentThread().interrupt();
            }
        }
        System.out.println("Thread Stopped.... ");
    }
}

public class Test2 {
    public static void main(String args[]) {
        StopThread thread = new StopThread();
        thread.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
    }
}

内容的提问来源于stack exchange,提问作者Võ Khắc Bảo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 23:45:09