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

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

    Follow one of below approaches.

    1. Iterate through all Future tasks, returned from submit on ExecutorService and check the status with blocking call get() on Future object as suggested by Kiran
    2. Use invokeAll() on ExecutorService
    3. CountDownLatch
    4. ForkJoinPool or Executors.html#newWorkStealingPool
    5. Use shutdown, awaitTermination, shutdownNow APIs of ThreadPoolExecutor in proper sequence

    Related SE questions:

    How is CountDownLatch used in Java Multithreading?

    How to properly shutdown java ExecutorService

提交回复
热议问题