多线程练习 斐波那契数列

该程序只是练习一下带返回值的线程,不注重算法

该程序运用算法第四版的时间函数

shutdown是必须写的,没有的话主线程不会停止

timer = new Stopwatch();
//一些代码
System.out.println(timer.elapsedTime());

计算出执行时间

import edu.princeton.cs.algs4.Stopwatch;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableTest {
	//得到第n个斐波那契数列的值
     private static int getVal(int n){
        if(n<3)
            return 1;
        else return getVal(n-1)+getVal(n-2);
    }
    public static void main(String...args) throws Exception{
        int count = 0;
        LinkedList<Future<Integer>> list = new LinkedList<>();
        ExecutorService ece = Executors.newCachedThreadPool();
        //小于等于40
        System.out.println("输入斐波那契数列个数");
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        Stopwatch timer = new Stopwatch();
        for (int i = 0; i < a; i++) {
            list.add(ece.submit(new MyCallable(i + 1)));
        }
        //没有这句话程序主线程不退出,即没有Process finished with exit code 0;
        ece.shutdown();
        System.out.println("多线程执行");
        //1 1 2 3 5
        while(!list.isEmpty()){
            if(list.getFirst().isDone()){
                count+=list.getFirst().get();
                list.removeFirst();
            }
        }
        System.out.println(count);
        System.out.println(timer.elapsedTime());

        count=0;

        timer = new Stopwatch();
        System.out.println("单线程执行");
        for(int i = 0;i<a;i++){
            count+=getVal(i+1);
        }
        System.out.println(count);
        System.out.println(timer.elapsedTime());
    }
}

class MyCallable implements Callable<Integer> {
    private int n;
    MyCallable(int n){
        this.n = n;
    }
    @Override
    public Integer call() {
        return getVal(n);
    }
    private int getVal(int n){
        if(n<3)
            return 1;
        else return getVal(n-1)+getVal(n-2);
    }
}

运行结果

输入斐波那契数列个数
40
多线程执行
267914295
0.275
单线程执行
267914295
0.641

输入斐波那契数列个数
35
多线程执行
24157816
0.045
单线程执行
24157816
0.058

输入斐波那契数列个数
30
多线程执行
2178308
0.023
单线程执行
2178308
0.006
数据少的时候单线程快。。。本练习只看写法,不讨论算法

发布了23 篇原创文章 · 获赞 4 · 访问量 839

猜你喜欢

转载自blog.csdn.net/qq_43656529/article/details/102004603
今日推荐