线程池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());
     }
 }
}

上一篇:PHP入门 - - 06-->HTML的表格标签


下一篇:Flink本地环境安装部署