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

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

    here is two options , just bit confuse which one is best to go.

    Option 1:

    ExecutorService es = Executors.newFixedThreadPool(4);
    List tasks = getTasks();
    CompletableFuture[] futures = tasks.stream()
                                   .map(task -> CompletableFuture.runAsync(task, es))
                                   .toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(futures).join();    
    es.shutdown();
    

    Option 2:

    ExecutorService es = Executors.newFixedThreadPool(4);
    List< Future> futures = new ArrayList<>();
    for(Runnable task : taskList) {
        futures.add(es.submit(task));
    }
    
    for(Future future : futures) {
        try {
            future.get();
        }catch(Exception e){
            // do logging and nothing else
        }
    }
    es.shutdown();
    

    Here putting future.get(); in try catch is good idea right?

提交回复
热议问题