线程池ExecutorService和完成服务CompletionService的使用获取线程的返回结果

package com.suning.ecif.admin.app.impl.temp;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class ClearCacheTaskPoolFactory {

 private static int t = 0;
    private static class TaskPoolHolder {
     //初始化固定大小的线程池
        private static final ExecutorService service = Executors.newFixedThreadPool(10);
        private static final CompletionService<Integer> cservice =
          new ExecutorCompletionService<Integer>(service);
    }

    private ClearCacheTaskPoolFactory() {
    }

    public static CompletionService<Integer> getInstance() {
        return TaskPoolHolder.cservice;
    }

    public static Future<Integer> submitTask(int i) {
        Callable<Integer> task = new ClearCacheTaskPoolFactory().new ClearCacheTask(i);
        return getInstance().submit(task);
    }

    class ClearCacheTask implements Callable<Integer> {
        public ClearCacheTask(int i) {
         t = i;
        }

        @Override
        public Integer call() throws Exception {
            return t;
        }
    }
    public static void main(String[] args) throws InterruptedException, ExecutionException {
     Collection<Future<Integer>> taskResults = new ArrayList<Future<Integer>>();
     for(int i = 0; i < 10; i++){
         taskResults.add(ClearCacheTaskPoolFactory.submitTask(i));
     }
     for(Future<Integer> future:taskResults){
         System.out.println(future.get());
     }
 }
}

posted @ 2016-09-19 10:05  前度刘郎  阅读(1200)  评论(0编辑  收藏  举报
欢迎来到戴建伟的博客!