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

前端 未结 26 2009
你的背包
你的背包 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:38

    So I post my answer from linked question here, incase someone want a simpler way to do this

    ExecutorService executor = Executors.newFixedThreadPool(10);
    CompletableFuture[] futures = new CompletableFuture[10];
    int i = 0;
    while (...) {
        futures[i++] =  CompletableFuture.runAsync(runner, executor);
    }
    
    CompletableFuture.allOf(futures).join(); // THis will wait until all future ready.
    

提交回复
热议问题