線程池工具類ThreadPoolUtils

線程池工具類ThreadPoolUtils

public class ThreadPoolUtils {

    private ThreadPoolExecutor pool = null;

//    static Integer num = 0;

    /**
     * 獲取對象
     * @param corePoolSize 核心線程數量
     * @param poolName 線程池名稱
     * @param maxThreadSize 最大線程數
     * @param maxTaskSize 最大阻塞任務數
     * @return
     */
    public ThreadPoolExecutor getNewInstance(int corePoolSize,int maxThreadSize,String poolName,int maxTaskSize){

        pool = createPool(corePoolSize,maxThreadSize,poolName,maxTaskSize);

        if(pool==null){
            throw new NullPointerException();
        }else{
            return pool;
        }
    }

    /**
     * 創建線程池
     * @param corePoolSize 核心線程數量
     * @param poolName 線程池名稱
     * @param maxThreadSize 最大線程數
     * @param maxTaskSize 最大阻塞任務數
     * @return
     */
    private ThreadPoolExecutor createPool(int corePoolSize,int maxThreadSize,String poolName,int maxTaskSize){

        return new ThreadPoolExecutor(corePoolSize,maxThreadSize,0,
                TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(maxTaskSize),
                new CustomThreadFactory(poolName),
                new RejectedExecutionHandlerImpl());
    }

    /**
     * 線程工廠
     * 給線程命名
     */
    private class CustomThreadFactory implements ThreadFactory{

        private final String poolName;

        public CustomThreadFactory(String poolName){
            this.poolName = poolName;
        }

        private AtomicInteger count = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            String nowThreadName = "";
            nowThreadName = poolName + count.addAndGet(1);
            t.setName(nowThreadName);
            return t;
        }
    }

    /**
     * 自定義拒絕策略
     */
    private class RejectedExecutionHandlerImpl implements RejectedExecutionHandler{

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try{
                System.out.println("重回隊列");
                executor.getQueue().put(r);
            }catch (Exception e){

            }
        }
    }

//    public static void main(String[] args){
//        ThreadPoolExecutor executor = new ThreadPoolUtils().getNewInstance(3,8,"test",5);
//        for (int i = 0;i<20;i++){
//            System.out.println("提交第"+i+"個任務");
//            executor.execute(()->{
//                try {
//                    System.out.println(Thread.currentThread().getName());
//                    TimeUnit.SECONDS.sleep(10);
//                    synchronized (num){
//                        System.out.println("數字爲:"+num++);
//                    }
//
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            });
//            System.out.println("提交第"+i+"個任務成功");
//        }
//        System.out.println("結束");
//    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章