jdk5以上自带线程池使用并返回结果
2015-04-28 17:22
288 查看
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>() { @Override public 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(); } } }
相关文章推荐
- Spring线程池和JDK线程池的区别及与FutureTask配合使用得到任务执行结果
- Java:多线程,线程池,使用CompletionService通过Future来处理Callable的返回结果
- Java:多线程,线程池,使用CompletionService通过Future来处理Callable的返回结果
- JDK自带线程池介绍及使用环境
- Java:多线程,线程池,使用CompletionService通过Future来处理Callable的返回结果
- Java:多线程,线程池,使用CompletionService通过Future来处理Callable的返回结果
- JDK自带线程池使用配置
- 使用jdk自带的线程池。加载10个线程。
- 线程池ExecutorService和完成服务CompletionService的使用获取线程的返回结果
- Java--使用ExecutorCompletionService 管理线程池处理任务的返回结果
- jQuery - Ajax - 与PHP集成可以使用json_encode返回结果
- 使用FastDateFormat来代替JDK自带的DateFormat
- 使用泛型封装返回结果以及使用委托封装try-catch流程
- Android 程式开发:(二)使用Intents链接Activities —— 2.3返回结果
- 修正win10部署JDK8(使用JDK文件夹中的自带JRE)
- golang通过反射使用json字符串调用struct的指定方法及返回json结果
- 在使用JS编程中,有时需要在一个方法返回两个个或两个以上的数据
- 获取Executor提交的并发执行的任务返回结果的两种方式/ExecutorCompletionService使用
- Querying Microsoft SQL Server 2012 读书笔记:查询和管理XML数据 1 -使用FOR XML返回XML结果集
- 使用jdk自带的工具监控tomcat服务器