Java 如何让未来依赖于另外两个人

How to make a future dependent on two others in Java

我有一个未来,理想情况下会采用来自其他两个未来的两个参数。为此我有 .thenCombine(),这里的技巧是第二个未来需要第一个的结果。

假设:

我想要这样的东西:

CompletableFuture<Customer> customerFuture = CompletableFuture.supplyAsync(() -> findCustomer(123));
CompletableFuture<Shop> shopFuture         = CompletableFuture.supplyAsync((customer) ->getAllAccessibleShops(customer));
CompletableFuture<Route> routeFuture       = customerFuture.thenCombine(shopFuture, (cust, shop) -> findRoute(cust, shop));

当然 thenCombine() 不是我要找的,上面的代码看起来很愚蠢,因为之后我不需要客户,但这只是一个例子。

有办法实现吗?

您的解决方案是正确的,唯一的问题是在 shopFuture 的声明中。您应该使用 thenApply[Async]() 以便它可以访问第一个的结果:

CompletableFuture<Customer> customerFuture = CompletableFuture.supplyAsync(() -> findCustomer(123));
CompletableFuture<Shop> shopFuture         = customerFuture.thenApply((customer) -> getAllAccessibleShops(customer));
CompletableFuture<Route> routeFuture       = customerFuture.thenCombine(shopFuture, (cust, shop) -> findRoute(cust, shop));

请注意,执行顺序保持顺序,因为 shopFuture 需要 customerFuture 的结果,而 routeFuture 需要 shopFuture 的结果。但是,如果您有额外的工作要做 CustomerShop,您可以使用额外的 thenApply[Async] 调用来 运行 它们。

如果您与这些结果没有任何关系,您可能希望将所有 3 个调用组合到一个 supplyAsync():

CompletableFuture<Route> customerFuture = CompletableFuture.supplyAsync(() -> {
   Customer customer = findCustomer(123));
   Shop shop = getAllAccessibleShops(customer));
   return findRoute(customer, shop)
});

另请参阅 CompletableFuture, supplyAsync() and thenApply() 以了解两者之间的行为差​​异。