import jsr166y.forkjoin.*;
class Fib extends RecursiveTask<Integer> { static final int threshold = 10; volatile int number; Fib(int n) { number = n; } public Integer compute () { int n = number; if (n <= threshold) return sequentialFib(n); else { Fib f1 = new Fib(n - 1); f1.fork(); Fib f2 = new Fib(n - 2); return f2.forkJoin() + f1.join(); } } public static void main(String[] args) { try { int groupSize = 2; // number of CPUs ForkJoinPool group = new ForkJoinPool(groupSize); Fib f = new Fib(40); Integer result =group.invoke(f); System.out.println(「Fibonacci Number: 「 + result); } catch (Exception ex) {} } int sequentialFib(int n) { if (n <= 1) return n; else return sequentialFib(n-1) + sequentialFib(n-2); } }
|