提问人:Rivo 提问时间:11/6/2023 更新时间:11/6/2023 访问量:62
CompletableFuture supplyAsyncmethod() 在 Java 中的工作原理
How CompletableFuture supplyAsyncmethod() works in Java
问:
下面是 completableFuture
https://www.baeldung.com/java-completablefuture 中的错误处理示例
CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> {
if (name == null) {
throw new RuntimeException("Computation error!");
}
return "Hello, " + name;
}).handle((s, t) -> s != null ? s : "Hello, Stranger!");
由于 handle() 方法将 BiFunction 作为参数,我的问题是 supplyAsync 如何将该参数传递给 handle()。我试图查看源代码,但没有找到。
是否可以用一些简单的例子来演示它,当方法用点链接时,函数是如何从一个方法传递到另一个方法的
首先Mehtod(..)。secondMethod(函数);
答: 暂无答案
评论
CompletableFuture<String> firstFuture = CompletableFuture.supplyAsync(() -> { if (name == null) { throw new RuntimeException("Computation error!"); } return "Hello, " + name; }); CompletableFuture<String> completableFuture = firstFuture.handle((s, t) -> s != null ? s : "Hello, Stranger!");
supplyAsync
handle
supplyAsync
handle
new StringBuilder().append(x).append(y)
supplyAsync
handle
Supplier
BiFunction
BiFunction
handle
Supplier<String> supplier = () -> { if (name == null) { throw new RuntimeException("Computation error!"); } return "Hello, " + name; }; BiFunction<? super String, Throwable, ? extends String> biFunction = (s, t) -> s != null ? s : "Hello, Stranger!"; CompletableFuture<String> firstStage = CompletableFuture.supplyAsync(supplier); CompletableFuture<String> completableFuture = firstStage.handle(biFunction);
Runnable r = () -> System.out.println("hello from " + Thread.currentThread().getName()); new Thread(r).start();
Runnable
CompletableFuture
CompletableFuture.supplyAsync(() -> "Hello", r -> new Thread(r).start()).thenAccept(System.out::println);