How to wait for all threads to finish, using ExecutorService?

前端 未结 26 2581
你的背包
你的背包 2020-11-22 01:55

I need to execute some amount of tasks 4 at a time, something like this:

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
    tas         


        
26条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 02:41

    In Java8 you can do it with CompletableFuture:

    ExecutorService es = Executors.newFixedThreadPool(4);
    List tasks = getTasks();
    CompletableFuture[] futures = tasks.stream()
                                   .map(task -> CompletableFuture.runAsync(task, es))
                                   .toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(futures).join();    
    es.shutdown();
    

提交回复
热议问题