首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java8、CompletableFuture

Java8、CompletableFuture
EN

Stack Overflow用户
提问于 2019-12-26 17:42:08
回答 1查看 86关注 0票数 0

在下面的代码片段中,有人可以让我知道当我们调用CompletableFuture.supplyAsync()时会发生什么,当一个值被返回时,它会在一个单独的线程中被返回吗?

代码语言:javascript
复制
// 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);
EN

回答 1

Stack Overflow用户

发布于 2019-12-26 18:57:09

这将返回一个新的可完成的Future对象,该对象基本上是在一个新的线程中执行的,该线程是从ForkJoinPool借用的。请参考javadoc -

代码语言:javascript
复制
/**
 * 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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59486544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档