Created
May 17, 2017 08:31
-
-
Save zhugw/248f2942ce955877a18a2f3f4fa4c68e to your computer and use it in GitHub Desktop.
ForkJoinPow
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 interview; | |
import java.util.concurrent.ForkJoinPool; | |
import java.util.concurrent.RecursiveTask; | |
/** | |
* Created by zhuguowei on 5/17/17. | |
*/ | |
public class ForkJoinPow extends RecursiveTask<Long> { | |
private int a; | |
private int b; | |
public ForkJoinPow(int a, int b) { | |
this.a = a; | |
this.b = b; | |
} | |
@Override | |
protected Long compute() { | |
// System.out.printf("%s %d%n",Thread.currentThread().getName(),b); | |
if(b == 1){ | |
return Long.valueOf(a); | |
} | |
// if(b == 2){ | |
// return Long.valueOf(a * a); | |
// } | |
int left = b/2; | |
ForkJoinPow leftResult = new ForkJoinPow(a, left); | |
leftResult.fork(); | |
ForkJoinPow rightResult = new ForkJoinPow(a, b - left); | |
return rightResult.compute() * leftResult.join(); | |
} | |
public static void main(String[] args) { | |
int a = 2; | |
int b = 30; | |
ForkJoinPow task = new ForkJoinPow(a, b); | |
ForkJoinPool pool = new ForkJoinPool(); | |
Long result = pool.invoke(task); | |
System.out.println(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment