问题描述
我有一个for循环,我正在尝试使用CompletableFuture进行并行化.
I have a for loop which I am trying to parallelize using CompletableFuture.
for (int i = 0; i < 10000; i++) {
doSomething();
doSomethingElse();
}
到目前为止,我所拥有的是:
What I have till now is:
for (int i = 0; i < 10000; i++) {
CompletableFuture.runAsync(() -> doSomething());
CompletableFuture.runAsync(() -> doSomethingElse());
}
我想这可以达到目的,但是在所有处理的开始和结束之前都需要打印日志.如果我这样做:
I guess this serves the purpose but there is a requirement to print log just before the start and end of all the processing. If I do this:
log("Started doing things");
for (int i = 0; i < 10000; i++) {
CompletableFuture.runAsync(() -> doSomething());
CompletableFuture.runAsync(() -> doSomethingElse());
}
log("Ended doing things");
这是否保证一旦所有for循环结束后第二个日志语句将被打印,因为它是在单独的线程中执行的?如果没有,有没有办法在不阻塞主线程的情况下做到这一点?
Does this guarantee that the second log statement will be printed once all the for loop is over since that is executing in a separate thread? If not, is there a way to do this without blocking the main thread?
推荐答案
您必须收集所有CompletableFuture,然后等待其完成:
You have to collect all CompletableFutures and wait for their complete:
log("Started doing things");
List<CompletableFuture> futures = new ArrayList();
for (int i = 0; i < 10000; i++) {
futures.add(CompletableFuture.runAsync(() -> doSomething()));
futures.add(CompletableFuture.runAsync(() -> doSomethingElse()));
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenRunAsync(() -> log("Ended doing things"));
或者当您使用ExecutorService时:
Or when you use the ExecutorService:
CompletableFuture.runAsync(() -> {
try {
executorService.invokeAll(tasks);
} catch (InterruptedException) {
e.printStackTrace();
}
log("Ended doing things");
});
这篇关于使用Java中的CompletableFuture并行执行for循环并记录执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!