java for循环 等待,使用Java中的CompletableFuture并行执行for循环并记录执行

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");

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?

解决方案

You have to collect all CompletableFutures and wait for their complete:

log("Started doing things");

List 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"));

Or when you use the ExecutorService:

CompletableFuture.runAsync(() -> {

try {

executorService.invokeAll(tasks);

} catch (InterruptedException) {

e.printStackTrace();

}

log("Ended doing things");

});

你可能感兴趣的:(java,for循环,等待)