repl.it
@djangofan/

RecusiveTaskFibonacci.java

Java

No description

fork
loading
Files
  • Main.java
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
// 2 recursive threads at the same time
// RecursiveAction returns void, so it wont work here
class Main {
	public static void main(String[] args) {
	  //System.out.print("Sequence: ");
		FibonacciCal fibonacciCal = new FibonacciCal(13);
		ForkJoinPool pool = new ForkJoinPool();
		int i = pool.invoke(fibonacciCal);
		System.out.println("\nFib result: " + i);
	}
}
class FibonacciCal extends RecursiveTask<Integer> {
	private static final long serialVersionUID = 1L;
	final int num;
	FibonacciCal(int num) { 
	  this.num = num;
	  //System.out.print(num + " ");
	}
	@Override
	protected Integer compute() {
	     if (num <= 1) return num;
	     FibonacciCal fcal1 = new FibonacciCal(num - 2);
	     fcal1.fork();
	     FibonacciCal fcal2 = new FibonacciCal(num - 1);
	     int sCalc = fcal2.compute();
	     int fCalc = fcal1.join();
	     System.out.print(sCalc + "-" + fCalc + " "); // only prints combinations of prime
	     return sCalc + fCalc; // n-2 + n-1
	}
}