# CompletableFuture Demo 一个用于学习 JDK `CompletableFuture` API 的 Java 17 / Maven 教学项目,包含配套的中文教程文档与可直接运行的代码示例(`Cf01`..`Cf10`)。 ## 技术栈 - JDK 17 - Maven(无第三方依赖,纯 JDK API) ## 目录结构 ``` completableFeature-demo/ ├── src/main/java/space/anyi/ # 示例代码,每个 API 主题一个文件,均有独立 main() ├── completablefuture-tutorial.md # 中文教程文档(循序渐进,配合示例代码) ├── completablefuture-blog.md # 面向资深 Java 程序员的速查/博客文档 ├── template.md # 写作风格与结构参考文档 └── todo.md # 待办任务清单 ``` ## 示例代码一览 | 文件 | 主题 | |------|------| | `Cf01_CreateStage` | 创建异步任务:`runAsync` / `supplyAsync` / `completedFuture` / `getNow` | | `Cf02_ThenSeries` | 串行处理:`thenApply` / `thenAccept` / `thenRun` | | `Cf03_ThenCombine` | 组合两个任务:`thenCombine` / `thenAcceptBoth` / `runAfterBoth` | | `Cf04_ThenEither` | 二选一:`applyToEither` / `acceptEither` / `runAfterEither` | | `Cf05_ThenCompose` | 展平组合:`thenCompose` | | `Cf06_AllOfAnyOf` | 批量聚合:`allOf` / `anyOf` | | `Cf07_ExceptionHandling` | 异常处理:`exceptionally` / `whenComplete` / `handle` | | `Cf08_ManualComplete` | 手动完成与状态查询:`complete` / `completeExceptionally` / `obtrudeValue` / `isDone` / `cancel` | | `Cf09_CustomExecutor` | 线程池与 Async 变体 | | `Cf10_TimeoutAndException` | 超时与异常链:`orTimeout` / `completeOnTimeout` / `exceptionallyCompose` | 详细讲解见 `completablefuture-tutorial.md`。 ## 构建与运行 ```bash mvn compile # 编译 mvn exec:java -Dexec.mainClass=space.anyi.Cf01_CreateStage # 运行某个示例 ``` ## 注意事项 - `exec:java` 需要显式指定 `-Dexec.mainClass`。 - Windows 下 PowerShell 会把未加引号的 `-Dexec.mainClass=...` 拆分,需要加引号:`'-Dexec.mainClass=space.anyi.Cf01_CreateStage'`。 - 控制台默认 GBK 编码,中文输出在终端可能乱码,程序本身是正确的。 - `Cf10`(使用 `orTimeout` / `completeOnTimeout`)在 `exec:java` 下会因 JDK 延迟调度线程残留而报线程组清理错误,属误报。请改用普通方式运行: ```bash java -cp target/classes space.anyi.Cf10_TimeoutAndException ```