ExecutorService, how to wait for all tasks to finish

前端 未结 15 2276
攒了一身酷
攒了一身酷 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条回答
  •  青春惊慌失措
    2020-11-22 16:43

    You can use ExecutorService.invokeAll method, It will execute all task and wait till all threads finished their task.

    Here is complete javadoc

    You can also user overloaded version of this method to specify the timeout.

    Here is sample code with ExecutorService.invokeAll

    public class Test {
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            ExecutorService service = Executors.newFixedThreadPool(3);
            List> taskList = new ArrayList<>();
            taskList.add(new Task1());
            taskList.add(new Task2());
            List> results = service.invokeAll(taskList);
            for (Future f : results) {
                System.out.println(f.get());
            }
        }
    
    }
    
    class Task1 implements Callable {
        @Override
        public String call() throws Exception {
            try {
                Thread.sleep(2000);
                return "Task 1 done";
            } catch (Exception e) {
                e.printStackTrace();
                return " error in task1";
            }
        }
    }
    
    class Task2 implements Callable {
        @Override
        public String call() throws Exception {
            try {
                Thread.sleep(3000);
                return "Task 2 done";
            } catch (Exception e) {
                e.printStackTrace();
                return " error in task2";
            }
        }
    }
    

提交回复
热议问题