Java parallel work iterator?

前端 未结 3 1401
后悔当初
后悔当初 2021-01-19 02:05

I\'m looking for a class where I can override a method to do the work, and return the results like an iterator. Something like this:

ParallelWorkIterator<         


        
3条回答
  •  萌比男神i
    2021-01-19 02:45

    Have a look at the ExecutorCompletionService. It does everything you want.

       void solve(Executor e, Collection> solvers)
         throws InterruptedException, ExecutionException {
           //This class will hold and execute your tasks
           CompletionService ecs
               = new ExecutorCompletionService(e);
           //Submit (start) all the tasks asynchronously
           for (Callable s : solvers)
               ecs.submit(s);
           //Retrieve completed task results and use them
           int n = solvers.size();
           for (int i = 0; i < n; ++i) {
               Result r = ecs.take().get();
               if (r != null)
                   use(r);
           }
       }
    

    The benefit of using a CompletionService is that it always returns the first completed result. This ensures you're not waiting for tasks to complete and it lets the uncompleted tasks run in the background.

提交回复
热议问题