ExecutorService, how to wait for all tasks to finish

前端 未结 15 2231
攒了一身酷
攒了一身酷 2020-11-22 15:45

What is the simplest way to to wait for all tasks of ExecutorService to finish? My task is primarily computational, so I just want to run a large number of jobs

15条回答
  •  Happy的楠姐
    2020-11-22 16:35

    Sounds like you need ForkJoinPool and use the global pool to execute tasks.

    public static void main(String[] args) {
        // the default `commonPool` should be sufficient for many cases.
        ForkJoinPool pool = ForkJoinPool.commonPool(); 
        // The root of your task that may spawn other tasks. 
        // Make sure it submits the additional tasks to the same executor that it is in.
        Runnable rootTask = new YourTask(pool); 
        pool.execute(rootTask);
        pool.awaitQuiescence(...);
        // that's it.
    }
    

    The beauty is in pool.awaitQuiescence where the method will block utilize the caller's thread to execute its tasks and then return when it is really empty.

提交回复
热议问题