基于不同的帖子和文章,我所知道的是: thenCompose 将在与前一阶段相同的线程中运行,而 thenComposeAsync 将尝试启动新的线程与前一阶段相比。
即使 Java 8 in Action 也提供以下代码,以证明 thenCompose 可以在相同的主题中使用。
引自 Java 8 in Action Chapter 11.4.3
BorderPane.alignment
但我尝试了下面的代码,结果让我很困惑,似乎 then thenCompose 将启动新线程,而 thenComposeAsync 将重用旧线程。
sudo apt-get install python-dev
结果如下:
public List<String> findPrices(String product) {
List<CompletableFuture<String>> priceFutures =
shops.stream()
.map(shop -> CompletableFuture.supplyAsync(
() -> shop.getPrice(product), executor))
.map(future -> future.thenApply(Quote::parse))
.map(future -> future.thenCompose(quote ->
CompletableFuture.supplyAsync(
() -> Discount.applyDiscount(quote), executor)))
.collect(toList());
return priceFutures.stream()
.map(CompletableFuture::join)
.collect(toList());
}
演示中有什么问题吗?请更正我或如果有一些有用的资源,请分享。