Java線程池詳解(二)
一、前言
在總結了線程池的一些原理及實現細節之後,產出了一篇文章:Java線程池詳解(一),後面的(一)是在本文出現之後加上的,而本文就成了(二)。因為在寫完第一篇關於java線程池的文章之後,越發覺得還有太多內容需要補充,每次都是修修補補,總覺得還缺點什麽。在第一篇中,我著重描述了java線程池的原理以及它的實現,主要的點在於它是如何工作的。而本文的內容將更為上層,重點在於如何應用java線程池,算是對第一篇文章的一點補充,這樣對於java線程池的學習和總結稍微完整一些。
使用過java線程池的人應該知道,我們都習慣使用Executors這個工廠類來獲取我們需要的線程池,而這個工廠不僅僅可以產生一種線程池,而是可以產生若幹種不同應用場景的線程池,你應當在合適的場景中使用合適的線程池,以保證最好的效率。下文將主要剖析這個類的一些細節,為了保證本文的相對獨立性,可能會提及一些在第一篇文章中提過的內容,這樣閱讀起來相對流暢一些,體驗更佳。本文依然不會基於java線程池做更多應用方面的描述,而是從線程池類型這個角度出發,試圖探索不同種類的線程池的特點和使用場景,從某種意義上來說,這樣描述的意義較於實際的例子來說更為有用。
“授人以魚不如授人以漁” !!!!
二、Executors工廠類詳解
介於本文的重點在於Executors這個工廠類,下面首先列出了Executors這個類提供的一些方法。
Executors方法本文需要對以上12個類做一些區分,從其特點出發,然後分析其應用場景。
- public static ExecutorService newFixedThreadPool(int nThreads)
使用這個方法會產生這樣一個線程池:線程池最多會保持nThreads個線程處於活動狀態,如果當前所有任務都處於活動狀態,那麽新提交的任務會被添加到任務阻塞隊列中去。總結一下就是:使用固定大小的線程池,並發數是固定的。
* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue. At any point, at most
* {@code nThreads} threads will be active processing tasks.
* If additional tasks are submitted when all threads are active,
* they will wait in the queue until a thread is available.
* If any thread terminates due to a failure during execution
* prior to shutdown, a new one will take its place if needed to
* execute subsequent tasks. The threads in the pool will exist
* until it is explicitly {@link ExecutorService#shutdown shutdown}.
- public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory)
相比於newFixedThreadPool(int nThreads), 你可以使用這個方法來傳遞你自己的線程工廠,線程工廠是用來幹嘛的?就是用來生成線程的,你可以使用線程工廠做一些個性化的線程特性定制。
- public static ExecutorService newWorkStealingPool(int parallelism)
在了解或者使用這個方法之前,你你該對java的Fork/Join並行框架有一些了解,如果你想要快速了解一下該部分的內容,可以參考這篇文章:Java Fork/Join並行框架。
從名字上我們就知道這個方法生產出來的線程池具有某種“小偷”的行為,在Fork/Join裏面,線程的工作模式為“盜竊算法”,也就是在自己的任務隊列消費完了之後不是進入等到狀態,而是會主動去偷竊別的線程的任務來做,其實是沒有一種獎勵機制來鼓勵這些線程去幫助別的線程去消費任務的,所以可以認為這些線程都是好人,都為了快速完成任務協調作戰。這種工作方式的重點在於,每個線程都將有一個任務隊列,線程之間通過“偷竊”的方式互相幫助來完成任務的消費。
可以看下這個方法的實現:
return new ForkJoinPool(parallelism, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true);
可以發現,這個方法不是使用我們在第一篇文章中分析了ThreadPoolExecutor來生成線程池。而是使用了ForkJoinPool,也就是Fork/Join裏面的線程池,關於ForkJoinPool更為深入的分析不再本文的涉及範圍內,你只要知道Fork/Join框架的一般運行原理就可以了,下面的描述可以幫助你決策你是否需要該方法提供的線程池來工作:
* Creates a thread pool that maintains enough threads to support
* the given parallelism level, and may use multiple queues to
* reduce contention. The parallelism level corresponds to the
* maximum number of threads actively engaged in, or available to
* engage in, task processing. The actual number of threads may
* grow and shrink dynamically. A work-stealing pool makes no
* guarantees about the order in which submitted tasks are
* executed.
- public static ExecutorService newWorkStealingPool()
參考newWorkStealingPool(int parallelism)。
- public static ExecutorService newSingleThreadExecutor()
下面是對該方法的描述:
* Creates an Executor that uses a single worker thread operating
* off an unbounded queue. (Note however that if this single
* thread terminates due to a failure during execution prior to
* shutdown, a new one will take its place if needed to execute
* subsequent tasks.) Tasks are guaranteed to execute
* sequentially, and no more than one task will be active at any
* given time. Unlike the otherwise equivalent
* {@code newFixedThreadPool(1)} the returned executor is
* guaranteed not to be reconfigurable to use additional threads.
可以從方法的名字上知道,該方法產生的線程池僅僅有一個Worker,任何時刻都將只有一個Worker在工作,添加的任務有很大概率被放在阻塞任務隊列中等待執行。這些任務會被順序執行,這個方法的返回值其實是對ThreadPoolExecutor的一層包裝,下面的代碼展示了最終執行任務的類:
static class DelegatedExecutorService extends AbstractExecutorService {
private final ExecutorService e;
DelegatedExecutorService(ExecutorService executor) { e = executor; }
public void execute(Runnable command) { e.execute(command); }
public void shutdown() { e.shutdown(); }
public List<Runnable> shutdownNow() { return e.shutdownNow(); }
public boolean isShutdown() { return e.isShutdown(); }
public boolean isTerminated() { return e.isTerminated(); }
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
return e.awaitTermination(timeout, unit);
}
public Future<?> submit(Runnable task) {
return e.submit(task);
}
public <T> Future<T> submit(Callable<T> task) {
return e.submit(task);
}
public <T> Future<T> submit(Runnable task, T result) {
return e.submit(task, result);
}
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException {
return e.invokeAll(tasks);
}
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException {
return e.invokeAll(tasks, timeout, unit);
}
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
return e.invokeAny(tasks);
}
public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return e.invokeAny(tasks, timeout, unit);
}
}
從上面的代碼可以看出,這個類其實就是使用了構造時傳遞的參數e來完成,更像是代理。而e是什麽?看下面的代碼:
ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())
其實就是一個只有一個線程的ThreadPoolExecutor。
- public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory)
參考newSingleThreadExecutor(),多了一個線程工廠參數。
- public static ExecutorService newCachedThreadPool()
首先看它的方法體內容:
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
可以看到,核心線程數量為0,而上限為Integer.MAX_VALUE,而且keepAliveTime為60秒,那麽這個線程池的工作模式為:只要有任務唄提交,而且當前沒有空閑的線程可用,那麽就會創建一個新的Worker來工作,一個線程工作完了之後會緩存(idle)60秒,如果60秒之內有新的任務提交,則會被喚醒進入工作模式,否則60秒後就會被回收。可以參考下面的描述:
* Creates a thread pool that creates new threads as needed, but
* will reuse previously constructed threads when they are
* available. These pools will typically improve the performance
* of programs that execute many short-lived asynchronous tasks.
* Calls to {@code execute} will reuse previously constructed
* threads if available. If no existing thread is available, a new
* thread will be created and added to the pool. Threads that have
* not been used for sixty seconds are terminated and removed from
* the cache. Thus, a pool that remains idle for long enough will
* not consume any resources. Note that pools with similar
* properties but different details (for example, timeout parameters)
* may be created using {@link ThreadPoolExecutor} constructors.
從描述上,我們可以想到,其實這種類型的線程池比較適合於短期高流量的場景,也就是我們所說的“秒殺”場景,在那樣的場景下,需要的線程數量較多,那麽使用該類型的線程池可以滿足,而且該線程池還有自動收縮的功能,在不需要那麽多線程的時候,會自動回收線程,釋放資源。
- public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory)
參考newCachedThreadPool()。
- public static ScheduledExecutorService newSingleThreadScheduledExecutor()
只有一個線程的調度線程池,類似於newSingleThreadExecutor,但是該方法生產的線程池具備調度功能,下面是對該方法的描述:
* Creates a single-threaded executor that can schedule commands
* to run after a given delay, or to execute periodically.
* (Note however that if this single
* thread terminates due to a failure during execution prior to
* shutdown, a new one will take its place if needed to execute
* subsequent tasks.) Tasks are guaranteed to execute
* sequentially, and no more than one task will be active at any
* given time. Unlike the otherwise equivalent
* {@code newScheduledThreadPool(1)} the returned executor is
* guaranteed not to be reconfigurable to use additional threads.
- public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory)
參考newSingleThreadExecutor和newSingleThreadScheduledExecutor。
- public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
參考newFixedThreadPool,但是返回類型不一樣。
- public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory)
參考newFixedThreadPool。
通過上面的分析,我們應該對java線程池的理解更為深入,再次說明,本文僅僅是對第一篇java線程池文章內容的補充,你應該首先閱讀第一篇文章:Java線程池詳解(一)之後再來閱讀本文,那樣內容上更完整,但是單獨閱讀本文一樣具備獨立性,但是收獲肯定沒有同時閱讀兩篇文章那樣多。
當然,還有許多需要補充的內容,比如Fork/Join框架的線程池的實現原理以及其細節,以及線程池使用的阻塞隊列的特點以及實現細節,這些內容要更為底層,需要的知識與要求的能力要多更高,會在以後的文章中陸續來探索。
轉載: https://www.jianshu.com/p/22c225a5ee59
Java線程池詳解(二)