Java – how to wait for all callables to complete execution before continuing?

I have the following hash code:

public class MyCallable implements Callable<Long> {
    @Override
    public Long call() throws Exception {
        // Do stuff...
    }
}

public class MyController {
    private ExecutorService executor = Executos.newCachedTreadPool();

    public Long concurrentDoStuff() {
        List<MyCallable> workers = makeWorkers();

        List<Long> allResults = new ArrayList<Long>();
        for(MyCallable worker : workers) {
            Future<Long> workerResults = executor.submit(worker);

            try {
                allResults.add(workerResults.get());
            } catch(InterruptedException ie) {
                // Handle...
            } catch(ExecutionException ee) {
                // Handle...
            }
        }

        // Question: how do I pause here and wait for all workers to finish?
    }
}

After the for loop, I want to wait for all workers to complete the task to continue What is the best / safest / most effective method? Thank you in advance!

Solution

You must use shutdown to close the executor and wait for all jobs to be processed using awaittermination

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>