java 8,CompletableFuture

标签 java java-8

在下面的代码片段中,谁能告诉我当我们调用 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/

相关文章:

Java 和 FTP 编辑在线文本文件

java - 模拟嵌套调用时出错

Java deepToString() 方法不适用于基元数组

如果在 List 或 Map 中对数组进行注释,则 Java 8 TYPE_USE 注释不起作用

使用正则表达式解析字符串时的 Java 8 lambda 表达式回调类型

java concurrency : many writers, 一个读者

java - 将库作为私有(private)包导入

java - JFrame 组件的这种奇怪的延迟是什么?

java - 为什么 Instant 不支持 ChronoUnit.YEARS 的操作?

java - 在此 Java Stream 用法中是否应该调用映射操作?