ExecutorService, how to wait for all tasks to finish

前端 未结 15 2118
攒了一身酷
攒了一身酷 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:33

    You could wait jobs to finish on a certain interval:

    int maxSecondsPerComputeDTask = 20;
    try {
        while (!es.awaitTermination(uniquePhrases.size() * maxSecondsPerComputeDTask, TimeUnit.SECONDS)) {
            // consider giving up with a 'break' statement under certain conditions
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);    
    }
    

    Or you could use ExecutorService.submit(Runnable) and collect the Future objects that it returns and call get() on each in turn to wait for them to finish.

    ExecutorService es = Executors.newFixedThreadPool(2);
    Collection> futures = new LinkedList<>();
    for (DataTable singleTable : uniquePhrases) {
        futures.add(es.submit(new ComputeDTask(singleTable)));
    }
    for (Future future : futures) {
       try {
           future.get();
       } catch (InterruptedException e) {
           throw new RuntimeException(e);
       } catch (ExecutionException e) {
           throw new RuntimeException(e);
       }
    }
    

    InterruptedException is extremely important to handle properly. It is what lets you or the users of your library terminate a long process safely.

提交回复
热议问题