thread48

来源:互联网 发布:陈一发儿淘宝店倒闭 编辑:程序博客网 时间:2024/06/06 19:31
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;    }}

原创粉丝点击