一、创建 CompletableFuture
CompletableFuture.supplyAsync(Supplier<U> supplier)
异步执行一个任务并返回结果。任务会在默认的线程池(ForkJoinPool.commonPool)中执行。java CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { return "Hello, World!"; });CompletableFuture.runAsync(Runnable runnable)
异步执行一个没有返回值的任务。java CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { System.out.println("Task executed"); });CompletableFuture.completedFuture(U value)
返回一个已经完成的CompletableFuture,并提供指定的结果。java CompletableFuture<String> future = CompletableFuture.completedFuture("Completed!");
二、处理结果
thenApply(Function<? super T,? extends U> fn)
在当前CompletableFuture完成后,应用一个函数来转换结果,并返回一个新的CompletableFuture。java CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello") .thenApply(s -> s + " World");thenAccept(Consumer<? super T> action)
在当前CompletableFuture完成后,消费结果但不返回新的结果。java CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> "Hello") .thenAccept(s -> System.out.println(s + " World"));thenRun(Runnable action)
在当前CompletableFuture完成后,执行一个不依赖于结果的操作。java CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> "Hello") .thenRun(() -> System.out.println("Task completed"));
三、组合多个 CompletableFuture
thenCompose(Function<? super T, ? extends CompletionStage<U>> fn)
当前CompletableFuture完成后,返回一个新的CompletableFuture,该新任务的结果将作为最终结果。java CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello") .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
将两个CompletableFuture的结果合并,并通过提供的函数处理这两个结果。java CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World"); CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (s1, s2) -> s1 + " " + s2);allOf(CompletableFuture<?>... cfs)
等待所有的CompletableFuture都完成。java CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2, future3);anyOf(CompletableFuture<?>... cfs)
只要有一个CompletableFuture完成就返回。java CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(future1, future2, future3);
四、异常处理
exceptionally(Function<Throwable, ? extends T> fn)
当CompletableFuture完成时发生异常时,使用提供的函数处理异常并返回一个替代结果。java CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { if (true) throw new RuntimeException("Error"); return "Hello"; }).exceptionally(ex -> "Error occurred: " + ex.getMessage());handle(BiFunction<? super T, Throwable, ? extends U> fn)
无论任务是否成功完成或抛出异常,都会调用handle方法来处理结果或异常。java CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { if (true) throw new RuntimeException("Error"); return "Hello"; }).handle((result, ex) -> ex != null ? "Error occurred" : result);
五、异步操作
thenApplyAsync(Function<? super T,? extends U> fn)
类似于thenApply,但会在不同的线程中执行。java CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello") .thenApplyAsync(s -> s + " World");thenAcceptAsync(Consumer<? super T> action)
类似于thenAccept,但会在不同的线程中执行。thenRunAsync(Runnable action)
类似于thenRun,但会在不同的线程中执行。
六、手动完成
complete(T value)
手动完成CompletableFuture并设置结果。java CompletableFuture<String> future = new CompletableFuture<>(); future.complete("Manually completed");completeExceptionally(Throwable ex)
手动完成CompletableFuture并抛出异常。java CompletableFuture<String> future = new CompletableFuture<>(); future.completeExceptionally(new RuntimeException("Manual exception"));
七、延迟执行
orTimeout(long timeout, TimeUnit unit)
如果在指定时间内未完成,则抛出TimeoutException。java CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) {} return "Hello"; }).orTimeout(1, TimeUnit.SECONDS);completeOnTimeout(T value, long timeout, TimeUnit unit)
如果在指定时间内未完成,则使用提供的值完成CompletableFuture。java CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) {} return "Hello"; }).completeOnTimeout("Timeout", 1, TimeUnit.SECONDS);