zoukankan      html  css  js  c++  java
  • 【java多线程】分段阶乘计算

    阶乘线程类:Factorial.java
    需要返回值,故实现Callable接口,call()返回计算结果

    import java.util.concurrent.Callable;
    
    public class Factorial implements Callable<Object>{
    
        private long val1;
        private long val2;
        private long sum;
        private long time;
        public Factorial(long val1, long val2) {
            this.val1 = val1;
            this.val2 = val2;
        }
    
        public  void  sum() throws InterruptedException {
            long temp =val1;
            for (long i = 1; i < val2 - val1 + 1; i++) {
                temp *= (val1+i);
            }
            sum = temp;
        }
    
        @Override
        public Object call() throws Exception {
    
            System.out.println("线程 "+ Thread.currentThread().getName() + ":运行,计算"+val1+"~"+val2+"的阶乘");
            long t1 = System.currentTimeMillis();
            sum();
            long t2 = System.currentTimeMillis();
            time = t2 - t1;
            System.out.println("线程 "+ Thread.currentThread().getName() + ":结束,执行时间"+time+"ms");
            return sum;
        }
    
        public long getTime() {
            return time;
        }
    
        public void setTime(long time) {
            this.time = time;
        }
    
    }
    

    Main.java:

    public class Main {
    
        public static void main(String[] args) throws InterruptedException, ExecutionException {
    
                Factorial c = new Factorial(1,10);
                FutureTask<Object> result = new FutureTask<Object>(c);
                new Thread(result).start();
    
                Factorial c2 = new Factorial(11,20);
                FutureTask<Object> result2 = new FutureTask<Object>(c2);
                new Thread(result2).start();
    
                long a = (long) result.get();
                long b = (long) result2.get();
    
                System.out.println("sum : "+(a*b));
        }
    
    }
  • 相关阅读:
    3.这个月有几天?
    3.这个月有几天?
    3.这个月有几天?
    2.求一个整数有几位(简单字符串操作)
    Algs4-1.2.1编写一个Point2D的用例-分治法
    Algs4-1.2.1编写一个Point2D的用例
    Algs4-1.1.39随机匹配
    Algs4-1.1.38二分查找与暴力查找
    Algs4-1.1.37糟糕的打乱
    Algs4-1.1.36乱序检查
  • 原文地址:https://www.cnblogs.com/cnsec/p/13286783.html
Copyright © 2011-2022 走看看