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
原创粉丝点击