1. 程式人生 > 其它 >執行緒池 詳解

執行緒池 詳解

三大方法

//Executors.newCachedThreadPool();  可伸縮的,遇強則強,遇弱則弱
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,// 最多21億
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}

//底層的阻塞佇列是LinkedBlockingQueue,它的預設請求佇列長度為Integer.MAX_VALUE;
//Executors.newFixedThreadPool(int nThreads);建立一個固定的執行緒池的大小
public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
}
    
/底層的阻塞佇列是LinkedBlockingQueue,它的預設請求佇列長度為Integer.MAX_VALUE;    
//Executors.newSingleThreadExecutor();   單個執行緒
public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
}

七大引數

//ThreadPoolExecutor的構造方法《  七大引數 》

 /**
     * 
     * @param corePoolSize  核心執行緒數
     * @param maximumPoolSize  最大執行緒數
     * @param keepAliveTime		執行緒保持alive時間,超時了沒有人呼叫就會釋放
     * @param unit				keepAliveTime超時單位
     * @param workQueue			阻塞佇列
     * @param threadFactory		執行緒工廠,建立執行緒的,一般不用動
     * @param handler			拒絕策略
     */
 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

四個拒絕策略

/**
* new ThreadPoolExecutor.AbortPolicy() // 		銀行滿了,還有人進來,不處理這個人的,丟擲異常
* new ThreadPoolExecutor.CallerRunsPolicy() // 哪來的去哪裡!
* new ThreadPoolExecutor.DiscardPolicy() //		佇列滿了,丟掉任務,不會丟擲異常!
* new ThreadPoolExecutor.DiscardOldestPolicy() //佇列滿了,嘗試去和最早的競爭,也不會丟擲異常!
*/  


/**
     * A handler for rejected tasks that runs the rejected task
     * directly in the calling thread of the {@code execute} method,
     * unless the executor has been shut down, in which case the task
     * is discarded.
     被拒絕任務的處理程式,直接在執行方法的呼叫執行緒中執行被拒絕的任務,除非執行程式已關閉,在這種情況下,任務將被丟棄。
     */
    public static class CallerRunsPolicy implements RejectedExecutionHandler {
      
        public CallerRunsPolicy() { }

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                r.run();
            }
        }
    }

    /**
     * A handler for rejected tasks that throws a
     * {@code RejectedExecutionException}.
     丟擲 RejectedExecutionException 的被拒絕任務的處理程式。
     */
    public static class AbortPolicy implements RejectedExecutionHandler {
        /**
         * Creates an {@code AbortPolicy}.
         */
        public AbortPolicy() { }

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
    }

    /**
     * A handler for rejected tasks that silently discards the
     * rejected task.
     被拒絕任務的處理程式,它默默地丟棄被拒絕的任務。
     */
    public static class DiscardPolicy implements RejectedExecutionHandler {
  
        public DiscardPolicy() { }
     
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        }
    }

    /**
     * A handler for rejected tasks that discards the oldest unhandled
     * request and then retries {@code execute}, unless the executor
     * is shut down, in which case the task is discarded.
     拒絕任務的處理程式,丟棄最舊的未處理請求,然後重試執行,除非執行程式被關閉,在這種情況下任務被丟棄。
     */
    public static class DiscardOldestPolicy implements RejectedExecutionHandler {
  
        public DiscardOldestPolicy() { }

  
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                e.getQueue().poll();
                e.execute(r);
            }
        }
    }