java 如何中断线程
中断线程的方法
在 Java 中,中断线程通常通过调用 Thread.interrupt() 方法实现。以下是几种常见的中断线程的方法和注意事项。
使用 Thread.interrupt()
调用目标线程的 interrupt() 方法可以中断线程。线程需要检查中断状态并做出响应。

Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 执行任务
}
System.out.println("线程被中断");
});
thread.start();
// 中断线程
thread.interrupt();
检查中断状态
线程可以通过 Thread.interrupted() 或 Thread.currentThread().isInterrupted() 检查中断状态。前者会清除中断标志,后者不会。

while (!Thread.interrupted()) {
// 执行任务
}
处理 InterruptedException
如果线程在阻塞状态(如 sleep()、wait()、join())时被中断,会抛出 InterruptedException,此时需要正确处理中断。
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// 恢复中断状态
Thread.currentThread().interrupt();
System.out.println("睡眠中被中断");
}
使用标志位中断线程
除了 interrupt(),也可以通过自定义标志位控制线程终止。
class MyRunnable implements Runnable {
private volatile boolean running = true;
public void stop() {
running = false;
}
@Override
public void run() {
while (running) {
// 执行任务
}
System.out.println("线程终止");
}
}
MyRunnable task = new MyRunnable();
Thread thread = new Thread(task);
thread.start();
// 终止线程
task.stop();
注意事项
- 中断线程并不会强制终止线程,只是设置中断标志,线程需要主动检查并处理。
- 忽略
InterruptedException可能导致线程无法正确终止,应在捕获异常后恢复中断状态。 - 使用
volatile标志位时,确保标志的可见性。
以上方法可以根据具体场景选择合适的方式中断线程。






