在java线程创建与运行中,isinterrupted() 方法用于检测当前线程是否被中断,它会返回中断状态并清除该标志位。要正确使用它,通常在循环或耗时操作中调用该方法来判断是否需要提前退出任务,从而响应取消请求。

如何在线程内部检查中断状态
在线程的 run 方法中,通过调用 Thread.currentThread().isInterrupted() 可以获取当前的中断标志。如果其他线程调用了 interrupt(),此方法将返回 true。开发者应在关键逻辑点(如循环条件、阻塞操作前)插入此检查,一旦发现中断,应执行清理工作并跳出循环,避免继续执行无效逻辑。

public class InterruptCheckTask implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Working...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// 恢复中断状态
Thread.currentThread().interrupt();
break;
}
}
System.out.println("Task terminated due to interrupt.");
}
}isInterrupted 与 interrupted 的区别
isInterrupted() 是实例方法,仅查询当前线程的中断状态而不改变它;而静态方法 interrupted() 会清除中断标志。在需要多次检查中断且不希望意外清除标志的场景下,应优先使用 isInterrupted()。例如,在多层嵌套调用中,若底层使用了 interrupted(),上层可能无法感知中断事件,导致资源泄漏或逻辑错误。
在代码库出现结构漂移之前,扫描JS或TS代码库中的禁止导入、循环依赖、孤立模块和其他依赖规则违规情况。
立即学习“Java免费学习笔记(深入)”;

public class CompareMethods {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
System.out.println("isInterrupted: " + Thread.currentThread().isInterrupted());
System.out.println("isInterrupted again: " + Thread.currentThread().isInterrupted());
});
t.start();
Thread.sleep(100);
t.interrupt();
t.join();
}
}捕获异常后如何保留中断信息
当 sleep 或 wait 等方法抛出 InterruptedException 时,JVM 会自动清除中断标志。此时若直接吞掉异常,外层代码将无法得知线程已被中断。正确的做法是在 catch 块中重新调用 Thread.currentThread().interrupt() 以恢复中断状态,确保调用链上的其他部分能检测到中断信号并做出相应处理。

















