gpt4 book ai didi

java 8,CompletableFuture

转载 作者:行者123 更新时间:2023-11-30 05:21:36 25 4
gpt4 key购买 nike

在下面的代码片段中,谁能告诉我当我们调用 CompletableFuture.supplyAsync() 时会发生什么以及返回值时会在单独的线程中返回吗?

// Run a task specified by a Supplier object asynchronously
CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "Result of the asynchronous computation";
}
});

// Block and get the result of the Future
String result = future.get();
System.out.println(result);

最佳答案

这会返回一个新的Completable Future对象,它基本上得到在借自 ForkJoinPool 的新线程中执行。请引用javadoc -

/**
* Returns a new CompletableFuture that is asynchronously completed
* by a task running in the {@link ForkJoinPool#commonPool()} with
* the value obtained by calling the given Supplier.
*
* @param supplier a function returning the value to be used
* to complete the returned CompletableFuture
* @param <U> the function's return type
* @return the new CompletableFuture
*/
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
return asyncSupplyStage(asyncPool, supplier);
}

关于java 8,CompletableFuture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59486544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com