我使用 ForkJoinPool 并行执行任务。当我查看我的程序的注销放置时,似乎 ForkJoinPool 创建了大量的工作人员来执行我的任务(有看起来像这样的日志条目:)05 Apr 2016 11:39:18,678 [ForkJoinPool-2-worker-2493] <message>
。
每个创建的任务是否有一个工作人员,然后根据我在 ForkJoinPool 中配置的并行数执行,还是我做错了什么?这是我的做法:
public class MyClass {
private static final int NUM_CORES = Runtime.getRuntime().availableProcessors();
public MyClass() {
int maxThreads = NUM_CORES * 2;
this.forkJoinPool = new ForkJoinPool(maxThreads);
}
public void doStuff() {
final int[] toIndex = {0};
forkJoinPool.submit(() -> {
List<ForkJoinTask> tasks = new ArrayList<>();
while (toIndex[0] < objects.size()) {
toIndex[0] += 20;
List<Object> bucket = objects.subList(toIndex[0] - 20, toIndex[0]);
ForkJoinTask task = new UpdateAction(bucket);
tasks.add(task);
task.fork();
}
tasks.forEach(ForkJoinTask::join);
}).join();
}
private class UpdateAction extends RecursiveAction {
private List<Object> bucket;
private UpdateAction(List<Object> bucket) {
this.bucket = bucket;
}
@Override
protected void compute() {
// do some calculation
}
}
}