Java并行工作迭代器? [英] Java parallel work iterator?

查看:158
本文介绍了Java并行工作迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一个类,我可以覆盖一个方法来完成工作,并像迭代器一样返回结果。类似这样的东西:

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<Result> itr = new ParallelWorkIterator<Result>(trials,threads) {

  public Result work() {
    //do work here for a single trial...
    return answer;
  }

};
while (itr.hasNext()) {
  Result result = itr.next();
  //process result...
}

用于monte carlo模拟等事情,但我不想处理设置线程池和管理返回线程每次。我滚动我自己的类希望完成这个,但我不够自信,我想检查如果这样的东西已经存在。

This is mainly going to be used for things like monte carlo simulations, but I don't want to have to deal with setting up thread pools and managing returning threads every time. I rolled my own class that hopefully accomplishes this, but I'm not confident enough in it and thought I'd check if something like this already existed.

编辑:要清楚,我希望它在后台继续运行,并在每个工作方法返回后排队结果,直到所有试验完成。因此,下一个方法可能会等待返回,直到队列中有结果。

To be clear, I want it to keep running in the background and queuing results after each work method returns until all trials have been completed. So the next method may wait to return until there is a result in the queue.

推荐答案

查看 ExecutorCompletionService

   void solve(Executor e, Collection<Callable<Result>> solvers)
     throws InterruptedException, ExecutionException {
       //This class will hold and execute your tasks
       CompletionService<Result> ecs
           = new ExecutorCompletionService<Result>(e);
       //Submit (start) all the tasks asynchronously
       for (Callable<Result> 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);
       }
   }

使用CompletionService的好处是它总是返回第一个完成的结果。这可以确保您不会等待任务完成,并且可以让未完成的任务在后台运行。

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.

这篇关于Java并行工作迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆