java 的 interrupt() 只是向线程发出协作式中断请求,线程需要检查标记或响应 interruptedexception 才能退出。发送请求后,再用带超时的 join() 等待,并通过 isalive() 确认是否真正结束。不要把调用 interrupt 成功当成线程已经停止,也不要用主线程 sleep 猜测退出时机。

中断可响应的工作线程,并用 join 等待结束
保存为 InterruptDemo.java,使用 JDK 17 编译运行。启动信号只用于确认线程已经进入工作方法,等待本身也有超时;工作线程在 sleep 被中断时恢复中断状态,然后走 finally 清理并返回。
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class InterruptDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch started = new CountDownLatch(1);
Thread worker = new Thread(() -> {
started.countDown();
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(1000);
}
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
} finally {
System.out.println("工作线程执行清理");
}
}, "demo-worker");
worker.start();
try {
if (!started.await(2, TimeUnit.SECONDS)) {
throw new IllegalStateException("工作线程未及时启动");
}
worker.interrupt();
worker.join(2000);
if (worker.isAlive()) {
throw new IllegalStateException("等待结束超时,线程仍在运行");
}
System.out.println("已确认线程退出");
} finally {
worker.interrupt();
}
}
}join(timeout) 返回不表示一定等到了线程结束,也可能是时间到了;所以后面必须检查 isAlive。若业务函数不响应中断,中断请求不会强制终止它,应另设 I/O 超时、资源关闭或其他协作退出机制。

立即学习“Java免费学习笔记(深入)”;
在没有阻塞方法的计算循环中主动检查中断
以下是可独立运行的 CpuInterruptDemo.java。循环主动检查 isInterrupted,不通过制造 InterruptedException 结束;清理放在 finally 中。示例里的计数只是演示负载,不要用于测量真实吞吐量。
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CpuInterruptDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch started = new CountDownLatch(1);
Thread worker = new Thread(() -> {
long count = 0;
started.countDown();
try {
while (!Thread.currentThread().isInterrupted()) {
count++;
}
} finally {
System.out.println("计算循环退出,计数=" + count);
}
});
worker.start();
try {
if (!started.await(2, TimeUnit.SECONDS)) throw new IllegalStateException("未启动");
worker.interrupt();
worker.join(2000);
if (worker.isAlive()) throw new IllegalStateException("未退出");
} finally {
worker.interrupt();
}
}
}不要每次循环执行一个永不响应中断的长耗时操作,再声称外层检查能立即停止它。中断响应速度由检查位置及内部操作共同决定。退出后的状态或输出也不应作为其他业务成功与否的替代判断。
区分 isInterrupted 与会清除标记的 interrupted
保存为 InterruptFlagDemo.java。isInterrupted 查询指定线程,不清除状态;Thread.interrupted 是静态方法,查询并清除当前线程的中断状态。sleep、wait、join 抛出 InterruptedException 时通常也会清除标记。
public class InterruptFlagDemo {
public static void main(String[] args) {
Thread current = Thread.currentThread();
current.interrupt();
if (!current.isInterrupted()) throw new AssertionError();
if (!current.isInterrupted()) throw new AssertionError("查询不应清除标记");
if (!Thread.interrupted()) throw new AssertionError();
if (current.isInterrupted()) throw new AssertionError("标记应已清除");
System.out.println("查询与清除行为检查通过");
}
}捕获中断异常后,可以继续向上抛给有处理责任的调用方,或在决定返回时恢复状态。不要无条件吞掉异常后继续原来的无限循环,否则停止请求可能被丢失。


















