zoukankan      html  css  js  c++  java
  • 合并计算

    /**
     * 线程池的作用:并行计算
     * 计算 1-200000 之间的质数
     */
    public class T07_ParallelComputing {
    
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            long start = System.currentTimeMillis();
            List<Integer> result = getPrime(1, 200000);
            long end = System.currentTimeMillis();
            System.out.println("主线程"+(end - start)); // 使用单线程计算的时间
    
            ExecutorService service = Executors.newFixedThreadPool(3);
            ComputeTask t1 = new ComputeTask(1, 100000);
            ComputeTask t2 = new ComputeTask(16000, 190000);
            ComputeTask t3 = new ComputeTask(190001, 200000);
            ComputeTask t4 = new ComputeTask(100001, 160000);  // 这里为什么不均分? 因为数字越大, 质数的数量就越多
            // 提交任务给ExecutorService执行
            Future<List<Integer>> f1 = service.submit(t1);
            Future<List<Integer>> f2 = service.submit(t2);
            Future<List<Integer>> f3 = service.submit(t3);
            Future<List<Integer>> f4 = service.submit(t4);
            // 执行开始
            start = System.currentTimeMillis();
            f1.get();
            f2.get();
            f3.get();
            f4.get();
            end = System.currentTimeMillis();
            System.out.println(end - start);
            service.shutdown();
        }
    
        static class ComputeTask implements Callable<List<Integer>> {
    
            private int start, end;
            
            ComputeTask (int start, int end) {
                this.start = start;
                this.end = end;
            }
    
            @Override
            public List<Integer> call() throws Exception {
                return getPrime(start, end);
            }
        }
        
    
        static boolean isPrime(int num) {
            for (int i = 2; i < num / 2; i++) {
                if (num % i == 0) return false;
            }
            return true;
        }
    
        /**
         * 返回指定范围的质数列表
         */
        static List<Integer> getPrime(int start, int end) {
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < end; i++) {
                if (isPrime(i)) list.add(i);
            }
            return list;
        }
    }
  • 相关阅读:
    Spring Security简介与入门Demo
    电商项目之多功能增删改查案例
    linux-用户管理
    zabbix3.4配置第三方邮件报警
    zabbix3.4配置客户端配置
    centos7上安装zabbix3.4的详细步骤与问题处理记录
    MyBatis日记(五):一对一关系,一对多关系
    MyBatis日记(四):MyBatis——insert、update、delete、select
    Python日记(二):Python之禅
    Python日记(一):拜见小主——Python
  • 原文地址:https://www.cnblogs.com/gxlaqj/p/11700483.html
Copyright © 2011-2022 走看看