Created
July 12, 2020 21:08
-
-
Save theboreddev/69b38c5352694bd59089f600eb777937 to your computer and use it in GitHub Desktop.
ForkJoinTak
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.theboreddev.examples.forkjoin; | |
import java.util.concurrent.ForkJoinPool; | |
import java.util.concurrent.ForkJoinTask; | |
import java.util.concurrent.RecursiveTask; | |
public class ForkJoinExample { | |
public static void main(String[] args) { | |
final int numberOfProcessors = Runtime.getRuntime().availableProcessors(); | |
final ForkJoinPool forkJoinPool = new ForkJoinPool(numberOfProcessors); | |
final ForkJoinTask<Integer> result = forkJoinPool.submit(new Fibonacci(30)); | |
System.out.println("The result is : " + result.join()); | |
} | |
static class Fibonacci extends RecursiveTask<Integer> { | |
private final int number; | |
public Fibonacci(int number) { | |
this.number = number; | |
} | |
@Override | |
protected Integer compute() { | |
if (number <= 1) { | |
return number; | |
} else { | |
Fibonacci fibonacciMinus1 = new Fibonacci(number - 1); | |
Fibonacci fibonacciMinus2 = new Fibonacci(number - 2); | |
fibonacciMinus1.fork(); | |
return fibonacciMinus2.compute() + fibonacciMinus1.join(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment