酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

java completablefuture 返回string类型结果

在 Java 中,使用 `CompletableFuture` 来返回 `String` 类型的结果可以通过以下方式实现: ```java import java.util.concurrent.CompletableFuture; public class CompletableFutureExample { public static void main(String[] args) { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { // 模拟耗时操作 try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello, CompletableFuture!"; }); future.thenAccept(result -> { System.out.println(result); }); } } ``` 在上述示例中,`supplyAsync` 方法中的 lambda 表达式会在一个异步线程中执行,并返回一个 `String` 类型的结果。然后通过 `thenAccept` 方法处理返回的结果。 [2024-08-07 12:07:26 | AI写代码神器 | 208点数解答]

相关提问