在下面的代码片段中,有人可以让我知道当我们调用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);发布于 2019-12-26 18:57:09
这将返回一个新的可完成的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);
}https://stackoverflow.com/questions/59486544
复制相似问题