How to wait for a ThreadPoolExecutor to finish

后端 未结 6 1726
渐次进展
渐次进展 2020-12-13 18:15

My Question: How to execute a bunch of threaded objects on a ThreadPoolExecutor and wait for them all to finish before moving on?

I\'m new to Thread

6条回答
  •  难免孤独
    2020-12-13 18:50

    Another approach is to use CompletionService, very useful if you have to attempt any task result:

    //run 3 task at time
    final int numParallelThreads = 3;
    
    //I used newFixedThreadPool for convenience but if you need you can use ThreadPoolExecutor
    ExecutorService executor = Executors.newFixedThreadPool(numParallelThreads);
    CompletionService completionService = new ExecutorCompletionService(executor);
    
    int numTaskToStart = 15;
    
    for(int i=0; i (or something you need)
        MyTask mt = new MyTask();
    
        completionService.submit(mt);
    }
    
    executor.shutdown(); //it cannot be queued more task
    
    try {
        for (int t = 0; t < numTaskToStart ; t++) {
            Future f = completionService.take();
            String result = f.get();
            // ... something to do ...
        }
    } catch (InterruptedException e) {
        //termination of all started tasks (it returns all not started tasks in queue)
        executor.shutdownNow();
    } catch (ExecutionException e) {
        // ... something to catch ...
    }
    

提交回复
热议问题