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; }}
阅读全文
0 0
- thread48
- POJ 2244 Eeny Meeny Moo 笔记
- UBOOT
- android 高级之旅 (四) 事件分发机制
- 文章标题
- Leetcode 543. Diameter of Binary Tree
- thread48
- 机智云STM32平台移植oled显示屏
- 欢迎使用CSDN-markdown编辑器
- 超小团队选择django还是flask? 题主的情况是这样
- Mac OS及Mac版Android studio安装consolas字体
- 二叉树给我的人生感悟
- Mybatis的一级缓存和二级缓存
- 亲测完美解决:服务器上出现应用程序错误。此应用程序的当前自定义错误设置禁止远程查看应用程序错误的详细信息(出于安全原因)
- java--习题