java 如何中断线程
中断线程的方法
在Java中,可以通过调用线程的interrupt()方法来请求中断线程。线程中断是一种协作机制,需要线程自身检查中断状态并做出响应。
设置中断标志
调用目标线程的interrupt()方法会设置线程的中断标志位:

Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 线程执行任务
}
});
thread.start();
// 请求中断线程
thread.interrupt();
检查中断状态
线程需要定期检查中断状态,可以通过以下方法:

// 检查中断标志
if (Thread.interrupted()) {
// 清理资源并退出
return;
}
// 或者在循环中检查
while (!Thread.currentThread().isInterrupted()) {
// 执行任务
}
处理阻塞状态
当线程处于阻塞状态(如wait()、sleep()、join()等),调用interrupt()会抛出InterruptedException:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// 恢复中断状态
Thread.currentThread().interrupt();
// 处理中断
}
强制终止线程(不推荐)
通过标记位控制线程终止是更安全的方式,而非使用已废弃的stop()方法:
volatile boolean running = true;
Thread thread = new Thread(() -> {
while (running) {
// 执行任务
}
});
thread.start();
// 终止线程
running = false;
注意事项
- 中断机制依赖线程的协作,无法强制停止不响应中断的线程
- 捕获
InterruptedException后通常应恢复中断状态 - 避免使用
stop()、suspend()等已废弃方法






