java如何中断thread
中断 Java 线程的方法
在 Java 中,中断线程主要通过 Thread.interrupt() 方法实现。以下是几种常见的中断线程的方式:
使用 Thread.interrupt()
调用目标线程的 interrupt() 方法会设置线程的中断标志位。线程可以通过检查 Thread.isInterrupted() 或捕获 InterruptedException 来响应中断。
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 执行任务
}
System.out.println("线程被中断");
});
thread.start();
// 中断线程
thread.interrupt();
捕获 InterruptedException
如果线程在阻塞状态(如 sleep()、wait()、join())时被中断,会抛出 InterruptedException。此时需要在 catch 块中处理中断逻辑。
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("线程在休眠时被中断");
Thread.currentThread().interrupt(); // 重新设置中断标志
}
});
thread.start();
// 中断线程
thread.interrupt();
使用标志位控制线程终止
通过自定义标志位(如 volatile boolean)控制线程终止,避免依赖中断机制。

class MyRunnable implements Runnable {
private volatile boolean isRunning = true;
public void stop() {
isRunning = false;
}
@Override
public void run() {
while (isRunning) {
// 执行任务
}
System.out.println("线程通过标志位终止");
}
}
MyRunnable task = new MyRunnable();
Thread thread = new Thread(task);
thread.start();
// 终止线程
task.stop();
注意事项
- 中断线程时需确保线程能够正确处理中断信号,避免资源泄漏或状态不一致。
- 如果线程未检查中断标志或未处理
InterruptedException,调用interrupt()可能无效。 - 避免直接使用
Thread.stop(),该方法已被废弃,可能导致数据不一致或资源泄漏。






