java如何取消执行
取消 Java 任务执行的方法
使用 Thread.interrupt()
通过调用线程的 interrupt() 方法设置中断标志,线程内部需检查 Thread.interrupted() 或捕获 InterruptedException 来响应中断。
Thread thread = new Thread(() -> {
while (!Thread.interrupted()) {
// 执行任务
}
});
thread.start();
// 取消任务
thread.interrupt();
使用 Future.cancel()
结合 ExecutorService 提交任务并返回 Future,调用 cancel(true) 尝试中断正在运行的任务。
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(() -> {
while (!Thread.interrupted()) {
// 执行任务
}
});
// 取消任务
future.cancel(true);
executor.shutdown();
使用自定义标志位
定义一个 volatile boolean 变量控制任务循环的执行。
volatile boolean isCancelled = false;
new Thread(() -> {
while (!isCancelled) {
// 执行任务
}
}).start();
// 取消任务
isCancelled = true;
处理阻塞操作的中断
若任务涉及 sleep、wait 或 I/O 操作,需捕获 InterruptedException 并恢复中断状态。

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 恢复中断状态
// 清理资源后退出
}
注意事项
- 避免直接调用
Thread.stop()(已废弃),可能导致数据不一致。 - 确保资源(如文件句柄、数据库连接)在取消时正确释放。
- 对不可中断的 I/O 操作(如
Socket),需关闭底层资源强制终止。






