線程池工具類

/**
 * @ClassName:SimpleThreadPoolUtil
 * @Desc: simple 線程池工具類
 **/
public class SimpleThreadPoolUtil {

    private static final Map<PoolType,ExecutorService> POOLS = new HashMap<>();

    public enum PoolType{
        TEST_THREAD_POOL
    }

    static {

        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("threadFacotry-%d").build();

        ExecutorService pool = new ThreadPoolExecutor(5, 5,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

        POOLS.put(PoolType.TEST_THREAD_POOL,pool);
    }

    /**
    * MethodName: getThreadPool
    * param: type 線程池類型
    * return:
    * describe: 獲取線程池
    **/
    public static ExecutorService getThreadPool(PoolType type){
        return POOLS.get(type);
    }


    /**
    * MethodName: submit
    * param: task 異步任務,type 線程池類型
    * return:  futuretask
    * describe: 根據指定類型線程池運行一個異步任務
    **/
    public static <T> Future<T> submit(Callable<T> task,PoolType type){

        ExecutorService pool = POOLS.get(type);

        if (pool == null || pool.isShutdown()){
            throw new IllegalArgumentException("pool not exists or had been shut down type:"+type);
        }

        return  pool.submit(task);
    }
}
相關文章
相關標籤/搜索