您的位置:首页 > 编程语言 > Java开发

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();
		}
	}
	
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐