【发布时间】:2020-09-13 14:08:16
【问题描述】:
我有一个方法 getCount(id) 从数据库中返回一个整数,作为 CompletableFuture。我想遍历所有的 id,得到所有的结果,并将它们添加到一个全局 int 中。然后我想用那个 int 做点什么:
int totalCount;
for (String id : API.getIDs()) {
//OtherAPI.getCount(id) will return the CompletableFuture<Integer>
OtherAPI.getCount(id).thenAccept(count -> totalCount += count);
}
System.out.println("" + totalCount);
这会报错,因为你不能在 thenAccept 中将一个整数加到另一个整数上,因为它是一个消费者。这样做的方法是什么?
【问题讨论】:
-
“行不通”是什么意思?编译器错误?运行时异常?意外行为?请edit发帖并提供必要的信息。
-
已添加,但我添加了更多“将不起作用”以明确表示无法以这种方式完成。
-
您不能更改 lambda 中的外部范围变量,因为该变量必须是最终的或有效最终的 wrt。拉姆达。您可以使用
AtomicInteger来避免此问题。 -
是的,我知道,但我不知道该怎么做。这就是这个问题的原因。
标签: java for-loop completable-future