一、Java 線程池
Java通過Executors提供四種線程池,分別為:
1、newCachedThreadPool:創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。(線程最大并發數不可控制)
2、newFixedThreadPool:創建一個定長線程池,可控制線程最大并發數,超出的線程會在隊列中等待。
3、newScheduledThreadPool:創建一個定長線程池,支持定時及周期性任務執行。
4、newSingleThreadExecutor:創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行。
線程池比較單線程的優勢在于:
a. 重用存在的線程,減少對象創建、消亡的開銷,性能佳。
b. 可有效控制最大并發線程數,提高系統資源的使用率,同時避免過多資源競爭,避免堵塞。
c. 提供定時執行、定期執行、單線程、并發數控制等功能。
參考:http://blog.csdn.net/nk_tf/article/details/51959276
二、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>()));
? ? }
可以看出這幾種線程池最終都是返回了ThreadPoolExecutor對象。
下面來看一下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;
? ? }
重點講解:
其中比較容易讓人誤解的是:corePoolSize,maximumPoolSize,workQueue之間關系。
1.當線程池小于corePoolSize時,新提交任務將創建一個新線程執行任務,即使此時線程池中存在空閑線程。
2.當線程池達到corePoolSize時,新提交任務將被放入workQueue中,等待線程池中任務調度執行
3.當workQueue已滿,且maximumPoolSize>corePoolSize時,新提交任務會創建新線程執行任務
4.當提交任務數超過maximumPoolSize時,新提交任務由RejectedExecutionHandler處理
5.當線程池中超過corePoolSize線程,空閑時間達到keepAliveTime時,關閉空閑線程
6.當設置allowCoreThreadTimeOut(true)時,線程池中corePoolSize線程空閑時間達到keepAliveTime也將關閉
那么學會使用ThreadPoolExecutor的參數后,我們就可以不用局限于最上面那四種線程池,可以按照需要來構建自己的線程池;
還有一點,通過ThreadFactory可以實現對線程的命名,舉例:
executor = Executors.newCachedThreadPool(new ThreadFactory() {? ? ? ? ? ? final AtomicInteger threadNumber = new AtomicInteger(1);? ? ? ? ? ? public Thread newThread(Runnable runnable) {? ? ? ? ? ? ? ? // Use our own naming scheme for the threads.? ? ? ? ? ? ? ? Thread thread = new Thread(Thread.currentThread().getThreadGroup(), runnable,"pool-spark" + threadNumber.getAndIncrement(), 0); //這里實現命名? ? ? ? ? ? ? ? // Make workers daemon threads.? ? ? ? ? ? ? ? thread.setDaemon(true);? ? ? ? ? ? ? ? if (thread.getPriority() != Thread.NORM_PRIORITY) {? ? ? ? ? ? ? ? ? ? thread.setPriority(Thread.NORM_PRIORITY);? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? return thread;? ? ? ? ? ? }? ? ? ? });
參考:http://blog.sina.com.cn/s/blog_9b7d76e30102wlz8.html