thread48 - 线程池在并行计算中案例

package com.neutron.t23;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 线程池案例
 * 线程池在并行计算中使用案例
 */
public class T237ParallelComputing {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        long start = System.currentTimeMillis();
        List<Integer> target = getPrime(1, 200000);
        long end = System.currentTimeMillis();
        System.out.println("f1:" + (end - start));

        final int cpuCoreNum = 4;
        ExecutorService service = Executors.newFixedThreadPool(cpuCoreNum);
        /* 为什么不平均分配呢? 我是没有想到啊,和质数计算有关系?*/
        ComputingTask task1 = new ComputingTask(1, 80000);
        ComputingTask task2 = new ComputingTask(80001, 130000);
        ComputingTask task3 = new ComputingTask(130001, 170000);
        ComputingTask task4 = new ComputingTask(170001, 200000);

        Future<List<Integer>> future1 = service.submit(task1);
        Future<List<Integer>> future2 = service.submit(task2);
        Future<List<Integer>> future3 = service.submit(task3);
        Future<List<Integer>> future4 = service.submit(task4);

        start = System.currentTimeMillis();
        List<Integer> i1 = future1.get();
        List<Integer> i2 = future2.get();
        List<Integer> i3 = future3.get();
        List<Integer> i4 = future4.get();

        i1.addAll(i2);
        i1.addAll(i3);
        i1.addAll(i4);

        end = System.currentTimeMillis();
        System.out.println("i2:" + (end - start));
    }

    static class ComputingTask implements Callable<List<Integer>> {
        int start;
        int end;

        public ComputingTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public List<Integer> call() throws Exception {
            return getPrime(this.start, this.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> lists = new ArrayList<>();
        for (int i = start; i <= end; i++) {
            if (isPrime(i)) {
                lists.add(i);
            }
        }
        return lists;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值