如何中断java线程
中断 Java 线程的方法
在 Java 中,中断线程是一种协作机制,通过设置线程的中断标志来通知线程应该停止执行。以下是几种常见的中断线程方法:
使用 interrupt() 方法
调用线程对象的 interrupt() 方法会设置线程的中断标志。线程需要检查中断状态并决定如何响应。
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 执行任务
}
});
thread.start();
thread.interrupt(); // 中断线程
检查中断状态
线程应在执行任务时定期检查中断状态,以便在收到中断请求时安全退出。
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
// 模拟任务执行
Thread.sleep(1000);
} catch (InterruptedException e) {
// 捕获中断异常后重新设置中断状态
Thread.currentThread().interrupt();
}
}
});
使用 Thread.interrupted() 方法
Thread.interrupted() 会检查当前线程的中断状态并清除中断标志。适用于需要一次性检查的场景。
Thread thread = new Thread(() -> {
while (!Thread.interrupted()) {
// 执行任务
}
});
处理阻塞操作的中断
当线程在阻塞操作(如 sleep()、wait() 或 I/O 操作)中被中断时,会抛出 InterruptedException,需捕获并处理。
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// 恢复中断状态或退出
Thread.currentThread().interrupt();
}
});
使用标志位控制线程退出
除了中断机制,还可以通过自定义标志位控制线程退出,适用于不支持中断的场景。

class MyRunnable implements Runnable {
private volatile boolean running = true;
public void stop() {
running = false;
}
@Override
public void run() {
while (running) {
// 执行任务
}
}
}
MyRunnable task = new MyRunnable();
Thread thread = new Thread(task);
thread.start();
task.stop(); // 停止线程
注意事项
- 中断机制是协作式的,线程需要主动检查中断状态或处理
InterruptedException。 - 捕获
InterruptedException后,通常应重新设置中断状态以保持中断信号。 - 避免使用已废弃的
stop()方法,因为它可能导致资源未释放或数据不一致。
通过合理使用中断机制或标志位,可以安全地终止 Java 线程。






