Skip to content

Instantly share code, notes, and snippets.

@zhugw
Created May 17, 2017 08:31
Show Gist options
  • Save zhugw/248f2942ce955877a18a2f3f4fa4c68e to your computer and use it in GitHub Desktop.
Save zhugw/248f2942ce955877a18a2f3f4fa4c68e to your computer and use it in GitHub Desktop.
ForkJoinPow
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