使用Fork/Join框架计算斐波那契

来源:互联网 发布:java开发文档怎么写 编辑:程序博客网 时间:2024/06/04 20:08

今天公司同事分享了Fork/Join框架

其中一个demo是使用了该框架计算斐波那契

看代码

import java.util.concurrent.ExecutionException;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.RecursiveTask;public class Fibonacci extends RecursiveTask<Long> {    private static final long serialVersionUID = 7875142223684511653L;    private final long     n;    private final int[] results = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ,144};    Fibonacci(long n) {        this.n = n;    }    private long compute(long small) {                return results[(int) small];    }        protected Long compute() {        if (n <= 12) {            return compute(n-1);        }        Fibonacci f1 = new Fibonacci(n - 1);        f1.fork();        Fibonacci f2 = new Fibonacci(n - 2);        f2.fork();        return f2.join() + f1.join();        // return f2.compute() + f1.join();     }    public static long fibonacci02(int n) {        if (n <= 0) {            return -1;        } else if (n == 1 || n == 2) {            return 1;        } else {            long start = 3;            long f = 1;//第1位            long b = 1;//第2位            while (start++ <= n) {                b = b + f;                f = b - f;            }            return b;        }    }    public static long fibonacci03(int n) {        if (n == 1) {            return 1;        }        if (n == 2) {            return 2;        }        return fibonacci03(n-1)+fibonacci03(n-2);    }        private static void sleep(long ms){    try {Thread.sleep(ms);} catch (InterruptedException e) {e.printStackTrace();}    }        public static void main(String[] args) throws InterruptedException, ExecutionException {    int n  = 40;        Fibonacci task = new Fibonacci(n);        ForkJoinPool pool = new ForkJoinPool(4);        long t0 = System.currentTimeMillis();        pool.invoke(task);        long t1 = System.currentTimeMillis();                System.out.printf("fjp cost %d,result:%d \n",t1-t0,task.get());  //      System.out.println(task.get());  //      System.out.println(task.getRawResult());                long t3 = System.currentTimeMillis();        long r = fibonacci02(n);        long t4 = System.currentTimeMillis();        System.out.printf("cost %d,result:%d \n",t4-t3,r);        long t5 = System.currentTimeMillis();        long k = fibonacci03(n);        long t6 = System.currentTimeMillis();        System.out.printf("cost %d,result:%d \n",t6-t5,k);    }        }

很明显第一种情况虽然使用了fork/join 但是复杂度是2^n次方啊 不过是多个线程一起跑的

第二种复杂度是n啊

这对比显然有问题啊 所有为了公平,我加了第三种 单线程情况下也是2^n的。

fjp cost 201,result:102334155 cost 0,result:102334155 cost 718,result:165580141 



原创粉丝点击