public static void main(String[] args) throws Exception {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("主线程开始 " + LocalDateTime.now().format(formatter));
Long invoke = new ForkJoinPool(100).invoke(new Fibonacci(1000));
System.out.println(invoke);
System.out.println("主线程结束 " + LocalDateTime.now().format(formatter));
}
static ConcurrentMap<Long, Long> concurrentMap = new ConcurrentSkipListMap<>();
static class Fibonacci extends RecursiveTask<Long> {
final long n;
Fibonacci(long n) {
this.n = n;
}
protected Long compute() {
if (n <= 1)
return n;
long n1 = this.n - 1;
Fibonacci f1 = new Fibonacci(n1);
f1.fork();
long n2 = this.n - 2;
Fibonacci f2 = new Fibonacci(n2);
//缓存优化
Long compute2 = concurrentMap.compute(n2, (key, oldValue) -> {
if (Objects.nonNull(oldValue)) {
//存在
//直接响应
return oldValue;
}
//不存在
//计算
return f2.compute();
});
Long compute1 = concurrentMap.compute(n1, (key, oldValue) -> {
if (Objects.nonNull(oldValue)) {
//存在
//直接响应
return oldValue;
}
//不存在
//计算
return f1.join();
});
return compute2 + compute1;
//正常计算
//return f2.compute()+ f1.join();
}
}
主线程开始 2021-08-10 12:39:48
817770325994397771
主线程结束 2021-08-10 12:39:48
1000次斐波那契数列如果是正常计算需要很久很久很久,缓存优化后1s内解决
参考资料:
斐波那契数列切入动态规划