12345678910111213141516171819202122232425262728293031323334353637 |
- import java.util.concurrent.*;
- public class TestForkjoin {
- public static void main(String[] args) throws Exception {
- MyRecursiveTask fj = new MyRecursiveTask(1, 100000);
- ForkJoinPool pool = new ForkJoinPool();
- Future<Integer> future = pool.submit(fj);
- System.out.println(future.get());
- }
- }
- class MyRecursiveTask extends RecursiveTask<Integer> {
- private final int threshold = 5;
- private int beg;
- private int end;
- MyRecursiveTask(int beg, int end) {
- this.beg = beg;
- this.end = end;
- }
- @Override
- protected Integer compute() {
- if (end - beg <= threshold) {
- int count = 0;
- for (int i = beg; i <= end; i++)
- count++;
- return count;
- }
- int mid = beg + (end - beg) / 2;
- MyRecursiveTask left = new MyRecursiveTask(beg, mid);
- MyRecursiveTask right = new MyRecursiveTask(mid + 1, end);
- left.fork();
- right.fork();
- return left.join() + right.join();
- }
- }
|