并行计算
Fork-Join
关键类
例子
``` package sumTest2; /** * 计算1-10000000的和 * 适用范围:计算不知道计算量大小的计算 */ import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask;public class SumTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ForkJoinPool pool = new ForkJoinPool();
SumTask task = new SumTask(1,10000000);//大任务
ForkJoinTask<Long> result = pool.submit(task);
//等待结果
do {
System.out.printf("Main: Thread Count: %d
",pool.getActiveThreadCount());//正在运行的线程
System.out.printf("Main: Paralelism: %d
",pool.getParallelism());//并行度
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (!task.isDone());
System.out.println(result.get().toString());
}
}
```java
package sumTest2;
import java.util.concurrent.RecursiveTask;
//继承这个可以自动递归
public class SumTask extends RecursiveTask<Long> {
private int start;
private int end;
public SumTask(int start, int end) {
this.start = start;
this.end = end;
}
public static final int Max= 5;
@Override
protected Long compute() {
Long sum = 0L;
boolean canCompute = (end - start)<= Max;
if (canCompute){
for (int i = start; i <= end; i++){
sum += i;
}
}else{
int middle = (end + start) / 2;
SumTask subTask1 = new SumTask(start, middle);
SumTask subTask2 = new SumTask(middle+1, end);
//invokeAll(subTask1, subTask2);
subTask1.fork();
subTask2.fork();
Long sum1 = subTask1.join();
Long sum2 = subTask2.join();
sum = sum1 + sum2;
}
return sum;
}
}