1 import EDU.oswego.cs.dl.util.concurrent.*; 2 3 4 12 13 public class Fib extends FJTask { 14 15 static int sequentialThreshold = 0; 17 18 public static void main(String [] args) { 19 try { 20 int procs; 21 int num; 22 try { 23 procs = Integer.parseInt(args[0]); 24 num = Integer.parseInt(args[1]); 25 if (args.length > 2) sequentialThreshold = Integer.parseInt(args[2]); 26 } 27 catch (Exception e) { 28 System.out.println("Usage: java Fib <threads> <number> [<sequntialThreshold>]"); 29 return; 30 } 31 32 FJTaskRunnerGroup g = new FJTaskRunnerGroup(procs); 33 Fib f = new Fib(num); 34 g.invoke(f); 35 g.stats(); 36 37 long result = f.getAnswer(); 38 System.out.println("Fib: Size: " + num + " Answer: " + result); 39 } 40 catch (InterruptedException ex) {} 41 } 42 43 44 volatile int number; 46 47 Fib(int n) { number = n; } 48 49 int getAnswer() { 50 if (!isDone()) throw new Error ("Not yet computed"); 51 return number; 52 } 53 54 55 public void run() { 56 int n = number; 57 58 if (n <= 1) { 60 } 62 else if (n <= sequentialThreshold) { 64 number = seqFib(n); 65 } 66 else { 68 Fib f1 = new Fib(n - 1); 70 Fib f2 = new Fib(n - 2); 71 72 coInvoke(f1, f2); 74 75 number = f1.number + f2.number; 77 } 79 } 80 81 static int seqFib(int n) { 83 if (n <= 1) 84 return n; 85 else 86 return seqFib(n-1) + seqFib(n-2); 87 } 88 89 } 90 91 | Popular Tags |