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

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

    Just to provide more alternatives here different to use latch/barriers. You can also get the partial results until all of them finish using CompletionService.

    From Java Concurrency in practice: "If you have a batch of computations to submit to an Executor and you want to retrieve their results as they become available, you could retain the Future associated with each task and repeatedly poll for completion by calling get with a timeout of zero. This is possible, but tedious. Fortunately there is a better way: a completion service."

    Here the implementation

    public class TaskSubmiter {
        private final ExecutorService executor;
        TaskSubmiter(ExecutorService executor) { this.executor = executor; }
        void doSomethingLarge(AnySourceClass source) {
            final List info = doPartialAsyncProcess(source);
            CompletionService completionService = new ExecutorCompletionService(executor);
            for (final InterestedResult interestedResultItem : info)
                completionService.submit(new Callable() {
                    public PartialResult call() {
                        return InterestedResult.doAnOperationToGetPartialResult();
                    }
            });
    
        try {
            for (int t = 0, n = info.size(); t < n; t++) {
                Future f = completionService.take();
                PartialResult PartialResult = f.get();
                processThisSegment(PartialResult);
                }
            } 
            catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } 
            catch (ExecutionException e) {
                throw somethinghrowable(e.getCause());
            }
        }
    }
    

提交回复
热议问题