默认情况下CompletableFuture
使用自己的 ForkJoinPool.commonPool() (请参阅CompletableFuture
实现)。并且该默认池仅创建守护程序 线程,例如,如果它们仍然存在,它们将不会阻止主应用程序终止。
您有以下选择:
将所有内容收集CompletionStage
到某个数组中,然后进行制作-这将确保在执行 join() 之后所有阶段都已完成java.util.concurrent.CompletableFuture#allOf()
.toCompletableFuture().join()
__
对您自己的仅包含 非守护程序 线程的线程池使用 * Async 操作,如以下示例所示: __
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(10, r -> {
Thread t = new Thread(r);
t.setDaemon(false); // must be not daemon
return t;
});
for (int i = 0; i < 100; i++) {
final int a = i;
// the operation must be Async with our thread pool
CompletableFuture<Boolean> cf = CompletableFuture.supplyAsync(() -> doPost(a), pool);
cf.thenRun(() -> System.out.printf("%s: Run_%s%n", Thread.currentThread().getName(), a));
}
pool.shutdown(); // without this the main application will be blocked forever
}
private static boolean doPost(int t) {
System.out.printf("%s: Post_%s%n", Thread.currentThread().getName(), t);
return true;
}