Java源碼閱讀之Executors

Summary:

  • 該類可以生成四種類型的線程池:
    • 不限定數量的線程池
    • 限定數量的線程池
    • 只有一個線程的線程"池"
    • 爲預定執行而構建的線程池
    • 前三者是用ThreadPoolExecutor來構建線程池的;返回的對象是一個ExecutorService;因爲ThreadPoolExecutor繼承了 AbstractExecutorService類,也就間接的實現了ExecutorService接口;
    • 後者特殊單獨講
  • 該類定義了內部適配器類,用於將Runnable轉換爲Callable類型,即變成帶返回值的運行方法,當然這個返回值默認值是null;在FuctureTash構造器會用到
  • 該類定義了一個線程工廠;從該工廠創建出來的線程都是非守護線程,優先級normal,的普通線程;在ThreadPoolExecutor構造器中被使用;

newCachedThreadPool:

//必要時創建新線程;空閒線程保留60秒
//這裏的SynchronousQueue是一個同步隊列,即size永遠爲0,存的數只有被取走才能再存一個;
//即如果當前沒有空線程則創建一個新線程;空線程保留60s後自動銷燬
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());  
}

newFixedThreadPool:

//包含固定數量的線程,空線程一直保留
//創建nThreads個線程,請求如果沒有空線程可以自行則存入LinkedBlockingQueue,該隊列可以存入的線程是無界的;(可能會耗盡系統資源!!!任務瘋漲的情況)
public static ExecutorService newFixedThreadPool(int nThreads){
    return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
}

newSingleThreadExecutor:

//只有一個線程的線程池
public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
}

newScheduledThreadPool

//預定執行而構建的固定線程池
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
}

內部類

DefaultThreadFactory 
//ThreadPoolExecutor會用到
static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" + poolNumber.getAndIncrement() +"-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false); //非守護線程
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
}

RunnableAdapter

//FuctureTask構造器會用到
//將Runnable轉化爲Callable<T>對象
public static <T> Callable<T> callable(Runnable task, T result) {
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
}
//RunnableAdapter是內部類,適配器模式
static final class RunnableAdapter<T> implements Callable<T> {
        final Runnable task;
        final T result;
        RunnableAdapter(Runnable task, T result) {
            this.task = task;
            this.result = result;
        }
        public T call() {
            task.run();
            return result;
        }
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章