ForkJoinPool 实现异步计算
前言
假设我们要计算一个未经优化的 Fibonacci 数
可以简单的写出以下代码:
static long fib(long n) {
if (n <= 2)
return 1L;
return fib(n - 1) + fib(n - 2);
}
使用ForkJoinPool
class Fib extends RecursiveTask<Long> {
private int n;
/**
* @param n
*/
public Fib(int n) {
this.n = n;
}
@Override
protected Long compute() {
if (n <= 2)
return 1L;
else {
Fib f1 = new Fib(n - 1);
Fib f2 = new Fib(n - 2);
invokeAll(f1, f2);
return f1.join() + f2.join();
}
}
}
二者比较
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class ForkJoinFib {
public static void main(String[] args) {
final int N = 34;
int times = 100;
ForkJoinPool fjp = new ForkJoinPool();
System.out.println("+----耗时测试----+");
long startTime = System.currentTimeMillis();
while (times-- != 0) {
Fib f = new Fib(N);
fjp.invoke(f);
}
System.out.println("用时: " + (System.currentTimeMillis() - startTime) + "毫秒");
times = 100;
System.out.println("+----耗时测试----+");
startTime = System.currentTimeMillis();
while (times-- != 0) {
fib(N);
}
System.out.println("用时: " + (System.currentTimeMillis() - startTime) + "毫秒");
}
static long fib(long n) {
if (n <= 2)
return 1L;
return fib(n - 1) + fib(n - 2);
}
}
class Fib extends RecursiveTask<Long> {
private int n;
/**
* @param n
*/
public Fib(int n) {
this.n = n;
}
@Override
protected Long compute() {
if (n <= 2)
return 1L;
else {
Fib f1 = new Fib(n - 1);
Fib f2 = new Fib(n - 2);
invokeAll(f1, f2);
return f1.join() + f2.join();
}
}
}
结果。。。
可能是创建对象那里时间用多了。。。
🤣