CompletableFuture有哪些方法
时间: 2025-07-10 13:09:21 浏览: 7
### `CompletableFuture` 类的常用方法列表及说明
Java 中的 `CompletableFuture` 是 Java 8 引入的一种强大的异步编程工具,它实现了 `Future` 和 `CompletionStage` 接口,支持链式调用、异常处理、任务组合等多种高级特性。以下是其常用方法及其功能说明。
---
#### 创建异步任务的方法
- **`supplyAsync(Supplier<U> supplier)`**
异步执行带有返回值的任务,默认使用 `ForkJoinPool.commonPool()` 线程池。
```java
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Result");
```
- **`supplyAsync(Supplier<U> supplier, Executor executor)`**
使用指定线程池异步执行有返回值的任务。
```java
ExecutorService executor = Executors.newFixedThreadPool(2);
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 42, executor);
```
- **`runAsync(Runnable runnable)`**
异步执行无返回值的任务,默认使用默认线程池。
```java
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("Task executed"));
```
- **`runAsync(Runnable runnable, Executor executor)`**
使用指定线程池异步执行无返回值的任务。
```java
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("Running in custom pool");
}, executor);
```
---
#### 对计算结果进行消费的方法
- **`thenApply(Function<T, R> fn)`**
对上一步的结果进行转换并返回新值,形成链式调用。
```java
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s.length());
```
- **`thenAccept(Consumer<T> action)`**
接收上一步的结果并消费处理,但不返回新值。
```java
CompletableFuture.supplyAsync(() -> 100)
.thenAccept(result -> System.out.println("Received: " + result));
```
- **`thenRun(Runnable action)`**
在前一个任务完成后执行一个无参数、无返回值的操作。
```java
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> "Data")
.thenRun(() -> System.out.println("Processing complete"));
```
---
#### 组合多个任务的方法
- **`thenCompose(Function<T, CompletionStage<U>> fn)`**
将当前任务的结果作为输入,生成一个新的 `CompletableFuture` 并串联执行。
```java
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 10)
.thenCompose(value -> CompletableFuture.supplyAsync(() -> value * 2));
```
- **`thenCombine(CompletionStage<U> other, BiFunction<T, U, V> fn)`**
合并两个任务的结果,并对它们进行联合处理。
```java
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 20);
future1.thenCombine(future2, (a, b) -> a + b);
```
- **`allOf(CompletableFuture<?>... futures)`**
等待所有给定的 `CompletableFuture` 完成,但不会返回结果。
```java
CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2);
```
- **`anyOf(CompletableFuture<?>... futures)`**
返回第一个完成的 `CompletableFuture` 的结果(可能是一个异常)。
```java
CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(future1, future2);
```
---
#### 异常处理方法
- **`exceptionally(Function<Throwable, ? extends T> fn)`**
捕获异常并提供一个默认值或替代逻辑。
```java
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) throw new RuntimeException("Error");
return 100;
}).exceptionally(ex -> -1);
```
- **`handle(BiFunction<T, Throwable, R> fn)`**
无论是否发生异常都会执行,用于统一处理结果和异常。
```java
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
return 100;
}).handle((result, ex) -> {
if (ex != null) {
System.err.println("Exception: " + ex.getMessage());
return -1;
}
return result;
});
```
- **`whenComplete(BiConsumer<T, Throwable> action)`**
在任务完成时执行回调,但不会改变最终结果。
```java
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 200)
.whenComplete((result, ex) -> {
if (ex != null) {
System.out.println("Task failed with exception: " + ex.getMessage());
} else {
System.out.println("Task completed with result: " + result);
}
});
```
---
#### 手动控制任务完成状态的方法
- **`complete(T value)`**
手动设置任务的结果,使其立即完成。
```java
CompletableFuture<String> future = new CompletableFuture<>();
future.complete("Manual Result");
```
- **`completeExceptionally(Throwable ex)`**
手动将任务标记为异常完成。
```java
future.completeExceptionally(new RuntimeException("Forced failure"));
```
---
#### 其他实用方法
- **`get()` 或 `join()`**
获取任务的执行结果,`join()` 不会抛出检查型异常。
```java
String result = future.join();
```
- **`isDone()`**
判断任务是否已完成。
```java
boolean done = future.isDone();
```
- **`orTimeout(long timeout, TimeUnit unit)`**(Java 9+)
设置任务超时时间,若未在规定时间内完成则抛出异常。
```java
future.orTimeout(3, TimeUnit.SECONDS);
```
- **`completeOnTimeout(T value, long timeout, TimeUnit unit)`**(Java 9+)
若任务未在规定时间内完成,则手动设置默认值。
```java
future.completeOnTimeout(-1, 2, TimeUnit.SECONDS);
```
---
###
阅读全文
相关推荐


















