我正在玩 fork/join 并想到以下示例:
App1
:2个for循环将一些随机数生成到anArrayList
中并将其传递给a fork
MyTask
(Fork):遍历ArrayLists
并添加所有数字,然后返回值
import java.util.ArrayList;
import java.util.concurrent.ForkJoinPool;
public class App1 {
ArrayList list = new ArrayList();
static final ForkJoinPool mainPool = new ForkJoinPool();
public App1() {
for (int i = 0; i < 10; i++) {
list.clear();
for (int j = 1000; j <= 100000; j++) {
int random = 1 + (int)(Math.random() * ((100 - 1) + 1));
list.add(random);
}
mainPool.invoke(new MyTask(list));
}
// At the end showing all results
// System.out.println (result1 + result2 + result3...);
}
public static void main(String[] args) {
App1 app = new App1();
}
}
import java.util.ArrayList;
import java.util.concurrent.RecursiveTask;
public class MyTask extends RecursiveTask<Integer> {
ArrayList list = new ArrayList();
int result;
public MyTask(ArrayList list) {
this.list = list;
}
@Override
protected Integer compute() {
for(int i=0; i<=list.size(); i++){
result += (int)list.get(i); // adding up all numbers
}
return result;
}
}
我不确定我是否走在正确的轨道上。我也不知道如何从分叉中收集所有结果。
有人可以看看我的代码吗?