【发布时间】:2018-11-18 11:53:05
【问题描述】:
我有一个 for 循环,我正在尝试使用 CompletableFuture 对其进行并行化。
for (int i = 0; i < 10000; i++) {
doSomething();
doSomethingElse();
}
我现在拥有的是:
for (int i = 0; i < 10000; i++) {
CompletableFuture.runAsync(() -> doSomething());
CompletableFuture.runAsync(() -> doSomethingElse());
}
我想这可以达到目的,但需要在所有处理的开始和结束之前打印日志。如果我这样做:
log("Started doing things");
for (int i = 0; i < 10000; i++) {
CompletableFuture.runAsync(() -> doSomething());
CompletableFuture.runAsync(() -> doSomethingElse());
}
log("Ended doing things");
这是否保证在所有 for 循环结束后将打印第二条日志语句,因为它是在单独的线程中执行的?如果没有,有没有办法在不阻塞主线程的情况下做到这一点?
【问题讨论】:
-
为什么要使用
CompletableFuture? (您似乎不再在循环之外使用这些对象,因此无需使用CompletableFutures。) -
为了保证循环在不阻塞主线程的情况下执行完毕
-
因此您不需要
CompletableFuture。 Java 中还有其他更适合此目的的机制。
标签: java multithreading future executorservice completable-future