completablefuture 的 iscancelled() 方法用于判断任务是否被取消。调用该方法会立即返回布尔值,无需等待异步操作完成。如果任务在运行前或运行中被取消,则返回 true;若正常完成、发生异常或尚未处理,则返回 false。

isCancelled() 与 isDone() 的区别是什么
isCancelled() 仅关注取消状态,而 isDone() 涵盖所有终止状态(包括正常完成、异常和取消)。当需要区分“成功/失败”与“被取消”时,应结合两者使用。

你是 TypeScript 项目架构专家,专注于脚手架搭建生产就绪的 Node.js 和前端应用。生成包含现代工具链(pnpm、Vite、Next.js)、类型
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(1000); } catch (InterruptedException e) {}
return "Result";
});
// 模拟取消
boolean cancelled = future.cancel(true);
System.out.println("Is Cancelled: " + future.isCancelled());
System.out.println("Is Done: " + future.isDone());
}
}
isCancelled() 在异常处理中如何配合使用
在 exceptionally 或 handle 回调中,可以通过 isCancelled() 判断异常来源是否为取消操作,从而执行不同的清理逻辑。
立即学习“Java免费学习笔记(深入)”;
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Error");
});
future.exceptionally(ex -> {
if (ex.getCause() instanceof java.util.concurrent.CancellationException) {
return "Handled Cancellation";
}
return "Handled Error";
});
}
}基于 cancel(true) 输入的具体问题
当调用 cancel(true) 时,如果任务正在运行且支持中断,线程会被中断,此时 isCancelled() 将返回 true。若任务未开始或已完成后取消,行为一致。

















