分支合并例子
class MyTask extends RecursiveTask<Integer> {
private static final Integer VALUE = 10;
private int begin;
private int end;
private int result;
public MyTask(int begin, int end){
this.begin = begin;
this.end = end;
}
@Override
protected Integer compute() {
if((end - begin) <= VALUE) {
for(int i = begin; i <= end; i++) {
result += i;
try {
TimeUnit.MICROSECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}else {
int mid = (begin + end) / 2;
MyTask task01 = new MyTask(begin, mid);;
MyTask task02 = new MyTask(mid + 1, end);
task01.fork();
task02.fork();
result = task01.join() + task02.join();
}
return result;
}
}
public class ForkJoinDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
MyTask myTask = new MyTask(0,100);
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);
Integer result = forkJoinTask.get();
System.out.println("result = " + result);
forkJoinPool.shutdown();
long end = System.currentTimeMillis();
System.out.println("花费时间:" + (end - start));
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
TimeUnit.MICROSECONDS.sleep(100);
}
System.out.println("sum = " + sum);
long end2 = System.currentTimeMillis();
System.out.println("花费时间:" + (end2 - end));
}
}