枪火工厂游戏
17.89MB · 2025-10-15
//立即完成
CompletableFuture<String> future = CompletableFuture.completedFuture("Hello");
//手动触发完成
CompletableFuture<String> future = new CompletableFuture<>();
future.complete("Result"); //正常完成
future.completeExceptionally(new RuntimeException("错误")); //异常完成
//异步执行有返回值的任务(默认使用 ForkJoinPool.commonPool() 线程池,建议指定线程池)
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "Async Result";
});
//异步执行无返回值的任务
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//doSomething
});
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> "Hello")
//处理结果,有参无返回值 Consumer:void accept(T t)
future.thenAccept(result -> System.out.println(result));
future.thenAcceptAsync 异步处理结果
//转换结果 有参有返回值 Function:R apply(T t)
future.thenApply(result -> result.toUpperCase());
future.thenApplyAsync 异步转换结果
//执行操作,无参无返回值 Runnable:void run()
future.thenRun(() -> System.out.println("Task completed"));
future.thenRunAsync 异步执行操作
//链式处理
future.thenApply(s -> s + " World")
.thenApply(String::toUpperCase)
.thenApplyAsync(this::validate) //thenApplyAsync 虽然是异步的,但后续的 thenAccept 仍会等待它完成
.thenAccept(validatedResult -> {
System.out.println(validatedResult);
this.saveToDB(validatedResult);
})
.thenRun(() -> System.out.println("Done"));
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
//顺序执行
future1.thenCompose(result -> CompletableFuture.supplyAsync(() -> result + " processed"));
//合并两个结果,并返回新值,用于数据转换
CompletableFuture<String> combined = future1.thenCombine(future2,
(result1, result2) -> result1 + " " + result2);
//并行执行等待所有完成
CompletableFuture<Void> all = CompletableFuture.allOf(future1, future2);
//等待任一完成
CompletableFuture<Object> any = CompletableFuture.anyOf(future1, future2);
//等待两个都完成后执行, 消费两个结果但不返回值
future1.thenAcceptBoth(future2, (result1, result2) ->
System.out.println(result1 + " " + result2));
//处理异常
future.exceptionally(throwable -> {
System.err.println("Error occurred: " + throwable.getMessage());
return "defaultValue"; //返回默认值
});
//统一处理结果和异常
future.handle((result, throwable) -> {
if (throwable != null) {
return "error handled";
}
return result; //可按需返回新的结果
});
//处理结果和异常
future.whenComplete((result, throwable) -> {
if (throwable != null) {
System.out.println("异常: " + throwable.getMessage());
} else {
System.out.println("结果: " + result);
}
});
Executor executor = Executors.newFixedThreadPool(4);
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> "任务", executor)
.thenApplyAsync(s -> s + "处理", executor);
//任一完成后执行
future1.applyToEither(future2, result -> "最快的结果: " + result);
//任一完成后消费
future1.acceptEither(future2, result -> System.out.println(result));
//检查完成状态
boolean isDone = future.isDone();
boolean isCancelled = future.isCancelled();
boolean isCompletedExceptionally = future.isCompletedExceptionally();
//取消任务
future.cancel(true); //等效于 future.completeExceptionally(new CancellationException())
//超时处理
CompletableFuture<String> timeoutFuture = CompletableFuture
.supplyAsync(() -> slowOperation())
.orTimeout(3, TimeUnit.SECONDS) //抛出 TimeoutException
.exceptionally(ex -> "超时默认值");
//3秒后如果未完成,用默认值完成
future.completeOnTimeout("default", 3, TimeUnit.SECONDS); //不会抛出异常
//延迟执行
future.completeAsync(() -> {}, CompletableFuture.delayedExecutor(5, TimeUnit.SECONDS));