java.util.concurrent.Executors類的常用方法介紹


Java 線程池

Executors提供了幾種線程池實現?

5個,分別如下

1、newCachedThreadPool:創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。(線程最大並發數不可控制)
2、newFixedThreadPool:創建一個定長線程池,可控制線程最大並發數,超出的線程會在隊列中等待。
3、newScheduledThreadPool:創建一個定長線程池,支持定時及周期性任務執行。
4、newSingleThreadExecutor:創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行。
5、newWorkStealingPool:jdk1.8新增,創建持有足夠線程的線程池來支持給定的並行級別,並通過使用多個隊列,減少競爭,它需要穿一個並行級別的參數,如果不傳,則被設定為默認的CPU數量。

使用線程池的好處

a. 重用存在的線程,減少對象創建、消亡的開銷,性能佳。
b. 可有效控制最大並發線程數,提高系統資源的使用率,同時避免過多資源競爭,避免堵塞。
c. 提供定時執行、定期執行、單線程、並發數控制等功能。

ThreadPoolExecutor機制

看看上面幾種線程池的實現代碼:

1、newCachedThreadPool

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

2、newFixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

3、newScheduledThreadPool

復制代碼
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }

public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }
復制代碼

4、newSingleThreadExecutor

復制代碼
public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
復制代碼

5、newWorkStealingPool

public static ExecutorService newWorkStealingPool() {
        return new ForkJoinPool
            (Runtime.getRuntime().availableProcessors(),
             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
             null, true);
    }

 

可以看出前四種線程池最終都是返回了ThreadPoolExecutor對象,最后一個返回的ForkJoinPool是jdk1.7才新增的

 

下面來看一下ThreadPoolExecutor的構造方法:

復制代碼
public ThreadPoolExecutor(int corePoolSize,//核心線程池大小
                              int maximumPoolSize,//最大線程池大小
                              long keepAliveTime,//線程池中超過corePoolSize數目的空閑線程最大存活時間;可以allowCoreThreadTimeOut(true)成為核心線程的有效時間
                              TimeUnit unit,//keepAliveTime的時間單位
                              BlockingQueue<Runnable> workQueue,//阻塞任務隊列
                              ThreadFactory threadFactory,//線程工廠
                              RejectedExecutionHandler handler) {//當提交任務數超過maxmumPoolSize+workQueue之和時,任務會交給RejectedExecutionHandler來處理
        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;
    }
復制代碼

再看一下ForkJoinPool的構造方法

public ForkJoinPool(int parallelism,
                        ForkJoinWorkerThreadFactory factory,
                        UncaughtExceptionHandler handler,
                        boolean asyncMode) {
        this(checkParallelism(parallelism),
             checkFactory(factory),
             handler,
             asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
             "ForkJoinPool-" + nextPoolId() + "-worker-");
        checkPermission();
    }

ThreadPoolExecutor和ForkJoinPool都繼承了AbstractExecutorService

重點講解: 
其中比較容易讓人誤解的是:corePoolSize,maximumPoolSize,workQueue之間關系。 

1.當線程池小於corePoolSize時,新提交任務將創建一個新線程執行任務,即使此時線程池中存在空閑線程。 
2.當線程池達到corePoolSize時,新提交任務將被放入workQueue中,等待線程池中任務調度執行 
3.當workQueue已滿,且maximumPoolSize>corePoolSize時,新提交任務會創建新線程執行任務 
4.當提交任務數超過maximumPoolSize時,新提交任務由RejectedExecutionHandler處理 
5.當線程池中超過corePoolSize線程,空閑時間達到keepAliveTime時,關閉空閑線程 
6.當設置allowCoreThreadTimeOut(true)時,線程池中corePoolSize線程空閑時間達到keepAliveTime也將關閉 

更多ThreadPoolExecutor的使用:http://www.cnblogs.com/shamo89/p/6694133.html

那么學會使用ThreadPoolExecutor的參數后,我們就可以不用局限於最上面那四種線程池,可以按照需要來構建自己的線程池

ThreadFactory的使用

Executors提供了一個默認的ThreadFactory,我們可以根據需求是否使用它,或者繼承它,或者實現ThreadFactory接口來自定義線程工廠需求。

DefaultThreadFactory的源碼

/**
     * The default thread factory
     */
    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();// 初始化ThreadGroup
            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;
        }
    }

可以看出,默認的DefaultThreadFactory實現了工廠類生成線程的一些基礎設置。

PrivilegedThreadFactory的介紹

PrivilegedThreadFactory繼承了DefaultThreadFactory,它主要是用於創建與當前線程具有相同的權限的新線程。具體源碼可以自行查看。

Ehcache里的NamedThreadFactory

在ehcache的包net.sf.ehcache.util里,有個NamedThreadFactory,功能實現和DefaultThreadFactory類似,它是直接實現ThreadFactory接口。

<T> Callable<T> callable(Runnable task, T result)

包裝runnable,使得線程具有返回值,result可以自定義。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM