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

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

    0 讨论(0)
  • 2020-11-22 02:56

    I've just written a sample program that solves your problem. There was no concise implementation given, so I'll add one. While you can use executor.shutdown() and executor.awaitTermination(), it is not the best practice as the time taken by different threads would be unpredictable.

    ExecutorService es = Executors.newCachedThreadPool();
        List<Callable<Integer>> tasks = new ArrayList<>();
    
        for (int j = 1; j <= 10; j++) {
            tasks.add(new Callable<Integer>() {
    
                @Override
                public Integer call() throws Exception {
                    int sum = 0;
                    System.out.println("Starting Thread "
                            + Thread.currentThread().getId());
    
                    for (int i = 0; i < 1000000; i++) {
                        sum += i;
                    }
    
                    System.out.println("Stopping Thread "
                            + Thread.currentThread().getId());
                    return sum;
                }
    
            });
        }
    
        try {
            List<Future<Integer>> futures = es.invokeAll(tasks);
            int flag = 0;
    
            for (Future<Integer> f : futures) {
                Integer res = f.get();
                System.out.println("Sum: " + res);
                if (!f.isDone()) 
                    flag = 1;
            }
    
            if (flag == 0)
                System.out.println("SUCCESS");
            else
                System.out.println("FAILED");
    
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    
    0 讨论(0)
提交回复
热议问题