gpt4 book ai didi

java - 按顺序运行异步操作

转载 作者:行者123 更新时间:2023-12-02 10:47:37 25 4
gpt4 key购买 nike

我有一系列 I/O 操作(DB、I/O 设备...),我需要按顺序运行。

@SafeVarargs
public final CompletableFuture<Boolean> execute(final Supplier<Boolean>... methods)
{
CompletableFuture<Boolean> future = null;

for (Supplier<Boolean> method : methods)
{
if (future == null)
{
future = CompletableFuture.supplyAsync(method, threadPool);
}
else
{
future.thenCombineAsync(CompletableFuture.supplyAsync(method, threadPool), (result, currentResult) -> result && currentResult,
threadPool);
}
}

return future.exceptionally(this::onException);
}

我的代码随机执行。

  1. 我可以做什么来确保订单?
  2. 最终如何合并结果?例如,如果一切都是真的?
  3. 在一切完成后应用回调来检查结果?

最佳答案

您当前的解决方案立即调用 supplyAsync(),然后尝试合并结果。

如果要保证顺序执行,应该使用thenApply()thenCompose()而不是thenCombine():

for (Supplier<Boolean> method : methods)
{
if (future == null)
{
future = CompletableFuture.supplyAsync(method, threadPool);
}
else
{
future = future.thenApplyAsync(result -> result && method.get(), threadPool);
}
}

请注意,如果下一个供应商中的任何一个返回 false,则不会调用下一个供应商的 method.get(),因为 && 是短路的。您可以使用单个 & 来强制调用,或者交换参数。

这已经合并了最后的所有 boolean 结果。您可以在循环后的结果 future 上添加任何内容,例如更多 thenApply() 调用,或阻塞 join() 调用来检索 boolean 值

请注意,这个循环也可以使用流轻松重写:

future = Arrays.stream(methods)
.reduce(CompletableFuture.completedFuture(true),
(f, method) -> f.thenApplyAsync(result -> result && method.get()),
(f1, f2) -> f1.thenCombine(f2, (result1, result2) -> result1 && result2));

关于java - 按顺序运行异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52441594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com