jdk5以上自带线程池使用并返回结果
来源:互联网 发布:淘宝有些不能用花呗 编辑:程序博客网 时间:2024/06/09 18:05
package com.eyugame.common.task;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;/** * jdk5以上自带线程池使用并返回结果 * * @author k560 * */public class TaskPoolUtil {private static ExecutorService executorService; private static void init(){ /*线程池大小按cpu核数*7*/int dbPoolSize = Runtime.getRuntime().availableProcessors() * 7;executorService = Executors.newFixedThreadPool(dbPoolSize); }public static <T> List<T> doTask(List<Callable<T>> callableList) throws InterruptedException, ExecutionException {if(executorService==null){init();}List<T> resultList = new ArrayList<T>();executorService.invokeAll(callableList);List<Future<T>> listFuture = new ArrayList<Future<T>>();for (Callable<T> task : callableList) {Future<T> future = executorService.submit(task);listFuture.add(future);}int countDownLatch = listFuture.size();while (true) {if (countDownLatch <= 0) {break;}Iterator<Future<T>> iter = listFuture.iterator();while (iter.hasNext()) {Future<T> ff = iter.next();if (ff.isDone()) {iter.remove();resultList.add(ff.get());countDownLatch--;}}}/*我在web项目西这个我是不关闭的*/executorService.shutdown();return resultList;}public static void main(String[] args) {List<Callable<Integer>> list=new ArrayList<Callable<Integer>>();for (int i = 0; i < 10; i++) {final int num=i+1;Callable<Integer> callable = new Callable<Integer>() {@Overridepublic Integer call() throws Exception {int m=num+9;Thread.sleep(1000);return m;}};list.add(callable);}try {List<Integer> iList=TaskPoolUtil.doTask(list);for (Integer integer : iList) {System.out.println(integer);}} catch (Exception e) {e.printStackTrace();}}}
0 0
- jdk5以上自带线程池使用并返回结果
- JDK5 获取线程返回结果
- 谨慎使用java自带线程池
- java自带线程池的使用
- Thread_CallableAndFuture(线程池返回结果)
- Mybatis+oracle 使用oracle自带的SYS_GUID() 并返回主键ID
- JDK5中的线程池
- 多线程 : 使用 Future 获取线程返回结果
- Java自带线程池
- windows 自带线程池
- Java自带线程池
- java自带线程池
- 使用微软自带精简版数据库 vs12 以上自带
- JDK5 线程池(java.util.concurrent.ThreadPoolExecutor) 使用介绍
- JDK5 如何获取所有线程池的结果再继续执行
- java自带的线程池ThreadPoolExecutor
- JDK自带线程池解析
- Jdk自带线程池实例
- 错误提示:accept: Invalid argument
- 位运算符
- Linux下抓包工具tcpdump应用详解
- 游戏开发要学什么?游戏开发如何快速入门就业?
- poj 3259 Wormholes
- jdk5以上自带线程池使用并返回结果
- 深入理解Git (六) - 松散对象
- SpringMVC学习系列(7) 之 格式化显示
- 前置和后置自增以及解引用重载函数(++、--、*)
- UVa 10617 Again Palindrome(回文串区间DP)
- ZIGBEE:发送函数AF_DataRequest详解
- android快捷开发框架xUtils简介和使用
- 数据结构 - 双向列表与循环列表
- Codeforces Round #300 A, B(背包dp), ..解题报告