如何终止java线程
终止 Java 线程的方法
使用标志位控制线程退出
通过设置一个布尔类型的标志位,线程在运行时检查该标志位,决定是否退出。这种方法安全且可控。
public class MyThread extends Thread {
private volatile boolean running = true;
public void stopRunning() {
running = false;
}
@Override
public void run() {
while (running) {
// 执行任务
}
}
}
volatile关键字确保多线程环境下标志位的可见性。调用stopRunning()方法可以安全终止线程。
使用interrupt()方法
Thread.interrupt()方法会设置线程的中断状态,线程可以通过检查中断状态决定是否退出。
public class MyThread extends Thread {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
// 执行任务
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 重新设置中断状态
}
}
}
}
调用thread.interrupt()会触发InterruptedException或设置中断状态,线程可以通过检查isInterrupted()退出循环。
避免使用stop()方法
Thread.stop()方法已被废弃,因为它会强制终止线程,可能导致资源未释放或数据不一致。应优先使用上述安全的方法。
使用ExecutorService管理线程
通过ExecutorService可以更优雅地管理线程生命周期,调用shutdown()或shutdownNow()终止线程池。
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 执行任务
}
});
executor.shutdownNow(); // 尝试终止所有线程
shutdownNow()会尝试中断所有正在执行的线程,但线程仍需响应中断才能退出。

总结
推荐使用标志位或interrupt()方法安全终止线程,避免直接调用stop()。对于线程池,使用ExecutorService提供的管理接口。






