jdk7 fork/join 性能测试-不如for循环~~很奇怪

本文介绍了如何利用Java的ForkJoinPool并行计算Fibonacci数列,并通过对比非并行计算方式,展示了并发处理在计算复杂任务时的性能提升。同时,提供了一种非递归实现方法来优化递归调用带来的性能损耗。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两种方法计算 Fibonacci

package jdk7;

import java.util.concurrent.RecursiveAction;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class Fibonacci extends RecursiveTask<Long>{
final int n;

Fibonacci(int n) {
this.n = n;
}

private Long compute(int small) {
final Long[] results = { 1l, 1l, 2l, 3l, 5l, 8l, 13l, 21l, 34l, 55l, 89l };
return results[small];
}

public Long compute() {
if (n <= 10) {
return compute(n);
}
// 分别计算每个 列表的 数据
// Fibonacci f1 = new Fibonacci(n - 1);
// Fibonacci f2 = new Fibonacci(n - 2);
//// System.out.println("fork new thread for " + (n - 1));
// f1.fork();
//// System.out.println("fork new thread for " + (n - 2));
// f2.fork();
// return f1.join() + f2.join();


Fibonacci f1 = new Fibonacci(n - 1);
f1.fork();
Fibonacci f2 = new Fibonacci(n - 2);
return f2.compute() + f1.join();
}

//非递归实现
public Long sum() {
long f1 = 1, f2 = 1;
long m = 0;
if (n <= 2) {
return 1l;
} else {
for (int i = 3; i <= n; i++) {
m = f1 + f2;
f2 = f1;
f1 = m;
}
return m;
}
}

public static void main(String args[]) throws InterruptedException, ExecutionException{
// Fibonacci f = new Fibonacci(100);
//
// long t1 = new Date().getTime();
// Integer i = f.compute();
// long t2 = new Date().getTime();
// System.out.println(i+"耗时:"+(t2-t1));
long t1 = new Date().getTime();
ForkJoinTask<Long> fjt = new Fibonacci(41);
ForkJoinPool fjpool = new ForkJoinPool();
fjpool.execute(fjt);
Long resultInt = fjt.get();
long t2 = new Date().getTime();

Long j = new Fibonacci(42).sum();
long t3 = new Date().getTime();
System.out.println(resultInt+"耗时:"+(t2-t1));
System.out.println(j+"耗时:"+(t3-t2));
}

}

结果如下:
fork/join 性能不如 for循环

267914296耗时:417
267914296耗时:0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值