job*_*job 5 java concurrency multithreading iterator
我正在寻找一个类,我可以覆盖一个方法来完成工作,并像迭代器一样返回结果.像这样的东西:
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...
}
Run Code Online (Sandbox Code Playgroud)
这主要用于monte carlo模拟之类的东西,但我不想每次都要处理设置线程池和管理返回线程.我推出了自己的课程,希望能够完成这一课,但我对此并不充分,并且认为我会检查这样的事情是否已经存在.
编辑:要清楚,我希望它在后台运行并在每个工作方法返回后排队结果,直到所有试验都完成.因此,下一个方法可能会等待返回,直到队列中出现结果.
Tim*_*Tim 13
看看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);
}
}
Run Code Online (Sandbox Code Playgroud)
使用CompletionService的好处是它总是返回第一个完成的结果.这可以确保您不会等待任务完成,并且可以让未完成的任务在后台运行.
归档时间: |
|
查看次数: |
5260 次 |
最近记录: |