其實在我眼里,線程池是一個很高端的東西,它會管理很多線程,并在進程中進行多線程的操作,是一個很高效且方便使用的東西。本篇文章就說說我對線程池的認識。
### 一,線程池的基本概念
線程池有很多優點,比如避免了重復創建和銷毀線程而降低了程序的運行效率,其次它可以很方便的控制線程的最大并發數,在一定程度上可以減少線程間的阻塞等。在android中線程池是由java的Executor實現的。它的真正實現類是ThreadPoolExecutor,下面是它的構造方法和相關介紹。
ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnalbe>workQueue,ThreadFactory threadFactory)
**corePoolSize:**核心線程數量,它會一直存在,沒任務就處理閑置狀態 。如果allowCoreThreadTimeOut設置為true,則閑置的核心線程會有超時策略,時間由keepAliveTime控制,當超時時,核心線程就會被終止。
**maximumPoolSize:**線程池能容納的最大線程數,當活動數達到這個數時,后續的新任務將會被阻塞。
**keepAliveTime:**超時時非核心線程會被回收,如果allowCoreThreadTimeOut設置為true,核心線程也會被回收。
**unit:**指定keepAliveTime的單位。TimeUnit.MILLISECONDS(毫秒),TimeUnit.SECONDS(秒)等。
**workQueue:**線程中的任務隊列,通過線程池的excute方法提交的Runnable會存儲到這參數中。
**threadFactory:**線程工廠,為線程池提供創建新線程的功能。
了解了上面的概念后,我們來看下android線程池的分類。
### 二,線程池的分類
1.FixedThreadPool
這是一種線程數量固定的線程池。處理空閑狀態時,并不會被回收,除非線程池關閉。它的源碼如下:
~~~
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
~~~
由上面介紹的ThreadPoolExecutor可知,FixedThreadPool的核心線程有nThreads條,最大線程也相同,這證明了它沒有非核心線程,且FixedThreadPool沒有超時策略,所以空閑時線程不會被回收。此外它的任務隊列也是無限大的。它適合用于需要快速響應的外界請求的情況下。接下來看下它的用法。
~~~
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
fixedThreadPool.execute(Runnable);
~~~
用法很簡單,只需要使用Executors就可創建FixedThreadPool,并初始化線程數。看到這個,以后開線程就不需要再用Thread了。
2.CacheThreadPool
是一種線程數量不定的線程池,只有非核心線程,并且最大線程數可以說是無窮大。當線程池中的線程都處于活動狀態時,創建新線程。這類線程適合執行大量耗時較少的任務。看下它的構造方法:
~~~
<pre name="code" class="java"><pre name="code" class="java"> public static final int MAX_VALUE = 0x7FFFFFFF;
~~~
~~~
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
~~~
同樣很好理解,沒有核心線程,最大線程婁是MAX_VALUE,基本可以理解成無上限,超時機制是60秒,由上分析可知,它在閑置60秒后會被回收,所以基本不占系統資源。看下它的用法。
~~~
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool.execute(runnable);
~~~
3.scheduledThreadPool
核心線程數量是固定的,而非核心線程數是沒有限制的,并且非核心線程閑置時會被立即回收,可用于執行定時和具有固定周期的重復任務。看下它的構造方法:
~~~
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
~~~
super就相當于調用了ThreadPoolExecutor,看下它的用法:
~~~
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);
// 1s后執行command
scheduledThreadPool.schedule(runnable, 1000, TimeUnit.MILLISECONDS);
// 延遲10ms后,每隔1000ms執行一次command
scheduledThreadPool.scheduleAtFixedRate(runnable, 10, 1000, TimeUnit.MILLISECONDS);
~~~
4.SingleThreadExecutor
內部只有一個線程,確保任務都在一個線程中按順序執行。這個多用于串行處理情況。不用考慮并發的問題。它的構造方法如下:
~~~
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
}
~~~
沒什么好解釋的,來看下它的用法:
~~~
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(runnable);</span>
~~~
分析完所有線程池后,我們得知,不同線程池有不同的應用環境,并沒有說哪個比較好。在實際情況中我們要根據自己的需求來適當的選擇。其實線程池在android的源碼中有大量的使用,下一篇博客將講解下AsyncTask的源碼解析,里面就運用了線程池。
- 前言
- Android底部tab與標題欄相結合
- Android免費獲取短信驗證碼
- android中Handler的源碼分析
- 詳解Fragment的傳值問題
- 詳談gson解析
- android新控件之toolbar,floatingActionButton,SnackBar,CollapsingToolbarLayout
- android自定義控件
- 淺談android的線程池
- Android的消息處理機制,AsyncTask源碼解析
- IPC——android進程間通信
- CoCos2d_android入門所需知道的一切
- Cocos2d_android你所需要知道的一切(下)
- Activity你需要知道的一切
- Activity啟動過程源碼分析
- Data Binding Guide——google官方文檔翻譯(上)
- Data Binding Guide——google官方文檔翻譯(下)
- android TextView實現跑馬燈效果
- android中生成excel
- Volley源碼解析
- LayoutInflater源碼解析
- android發送郵件
- android測試工具MonkeyRunner--google官網翻譯
- android View繪制源碼分析
- Android中Window添加View的底層原理
- 仿美團商品選購下拉菜單實現