|
|
@@ -0,0 +1,39 @@
|
|
|
+package space.anyi;
|
|
|
+
|
|
|
+import java.util.concurrent.CompletableFuture;
|
|
|
+
|
|
|
+public class Cf08_ManualComplete {
|
|
|
+ public static void main(String[] args) throws Exception {
|
|
|
+ // complete: 任务的完成时机由我们手动决定(比如等待外部事件/用户操作)
|
|
|
+ CompletableFuture<String> gate = new CompletableFuture<>();
|
|
|
+ new Thread(() -> {
|
|
|
+ try {
|
|
|
+ Thread.sleep(500);
|
|
|
+ } catch (InterruptedException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ gate.complete("外部线程触发了完成");
|
|
|
+ }).start();
|
|
|
+ System.out.println("阻塞等待手动完成: " + gate.join());
|
|
|
+
|
|
|
+ // completeExceptionally: 手动让任务以异常结束,常用于"超时兜底"
|
|
|
+ CompletableFuture<Integer> timeout = new CompletableFuture<>();
|
|
|
+ timeout.completeExceptionally(new RuntimeException("调用超时,兜底结束"));
|
|
|
+ try {
|
|
|
+ timeout.join();
|
|
|
+ } catch (Exception e) {
|
|
|
+ System.out.println("completeExceptionally 抛给调用方: " + e.getCause());
|
|
|
+ }
|
|
|
+
|
|
|
+ // obtrudeValue: 无论之前是否已完成,强制覆盖为新值(慎用)
|
|
|
+ CompletableFuture<String> forced = CompletableFuture.completedFuture("旧结果");
|
|
|
+ forced.obtrudeValue("强制更新的结果");
|
|
|
+ System.out.println("obtrudeValue 覆盖后: " + forced.join());
|
|
|
+
|
|
|
+ // cancel: 取消任务, isCancelled 与 isCompletedExceptionally 都会为 true
|
|
|
+ CompletableFuture<String> cancelling = new CompletableFuture<>();
|
|
|
+ System.out.println("cancel() 返回值: " + cancelling.cancel(true));
|
|
|
+ System.out.println("取消后 isCancelled: " + cancelling.isCancelled()
|
|
|
+ + ", isCompletedExceptionally: " + cancelling.isCompletedExceptionally());
|
|
|
+ }
|
|
|
+}
|