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

前端 未结 26 2398
你的背包
你的背包 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: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> tasks = new ArrayList<>();
    
        for (int j = 1; j <= 10; j++) {
            tasks.add(new Callable() {
    
                @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> futures = es.invokeAll(tasks);
            int flag = 0;
    
            for (Future 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();
        }
    

提交回复
热议问题