Future怎么转换成CompletableFuture
时间: 2023-12-02 11:43:03 浏览: 169
可以使用CompletableFuture类的静态方法completedFuture()将Future对象转换为CompletableFuture对象。下面是两个示例代码,分别使用makeCompletableFuture()和transformDoneFuture()方法将Future对象转换为CompletableFuture对象:
```java
// 使用makeCompletableFuture()方法将Future对象转换为CompletableFuture对象
public static CompletableFuture makeCompletableFuture(Future future) {
return CompletableFuture.supplyAsync(() -> {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
});
}
// 使用transformDoneFuture()方法将Future对象转换为CompletableFuture对象
private static CompletableFuture transformDoneFuture(Future future) {
return CompletableFuture.completedFuture(null).thenApplyAsync(v -> {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
});
}
```
阅读全文