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