ThreadPoolExecutor(線程池)
構(gòu)造方法
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
具體參數(shù)及其含義
int corePoolSize
核心線程數(shù)量玄捕,核心線程存在兩種狀態(tài)鲜漩,與參數(shù)設(shè)置有關(guān)殉簸。
??存活狀態(tài):allowCoreThreadTimeOut 默認(rèn)設(shè)置為false侧到,此設(shè)置下奶浦,核心線程一直處于存活狀態(tài)略就,即使核心線程無(wú)任務(wù)操作捎迫,處于空閑狀態(tài)。
??終止?fàn)顟B(tài): allowCoreThreadTimeOut 設(shè)置為true時(shí)表牢,超過(guò)keepAliveTime設(shè)定時(shí)常后窄绒,核心線程終止,被回收崔兴。int maximumPoolSize
線程池所允許存在的最大線程數(shù)量彰导,超過(guò)最大線程數(shù)后,后續(xù)的新任務(wù)會(huì)被阻塞敲茄。long keepAliveTime
當(dāng)線程處于空閑狀態(tài)后位谋,允許存活的時(shí)長(zhǎng),超過(guò)此時(shí)長(zhǎng)后堰燎,線程會(huì)被終止回收掏父。根據(jù)allowCoreThreadTimeOut參數(shù)不同,限定的線程不同爽待。
??限定非核心線程:當(dāng)allowCoreThreadTimeOut參數(shù)值為默認(rèn)false時(shí)损同,只對(duì)非核心線程有限制。
??限定核心線程與非核心線程:當(dāng)allowCoreThreadTimeOut參數(shù)值為true時(shí)鸟款,對(duì)線程池中的核心與非核心都由限制膏燃,超過(guò)限定時(shí)長(zhǎng)后,線程都會(huì)終止并回收何什。TimeUnit unit
keepAliveTime的事件單位组哩,TimeUnit類提供枚舉宏侍,有納秒黄娘、微秒、毫秒等娃肿,具體如下罐栈。
TimeUnit.NANOSECONDS:納秒
TimeUnit.MICROSECONDS:微秒
TimeUnit.MILLISECONDS:毫秒
TimeUnit.SECONDS:秒
TimeUnit.MINUTES:分
TimeUnit.HOURS:小時(shí)
TimeUnit.DAYS:天
BlockingQueue<Runnable> workQueue
線程池任務(wù)隊(duì)列黍衙,阻塞隊(duì)列,主要用來(lái)存儲(chǔ)已經(jīng)提交但尚未分配給線程執(zhí)行的任務(wù)(線程池execute方法提交的Runnable對(duì)象)荠诬。ThreadFactory threadFactory
線程工廠琅翻,interface類型位仁,只有一個(gè)方法Thread newThread(Runnable r); 用來(lái)為線程池創(chuàng)建新線程。RejectedExecutionHandler handler
interface類型方椎,只有一個(gè)方法void rejectedExecution(Runnable r, ThreadPoolExecutor executor)聂抢,線程池?zé)o法執(zhí)行新任務(wù)時(shí),ThreadPoolExecutor調(diào)用handler的該方法通知調(diào)用者棠众。
調(diào)用策略
- 如果線程池中線程的數(shù)量小于核心線程數(shù)量琳疏,新任務(wù)來(lái)之后,開啟新的核心線程去執(zhí)行任務(wù)闸拿。
- 如果線程池中核心線程數(shù)量已經(jīng)飽和空盼,新任務(wù)來(lái)之后,則放到workQueue任務(wù)隊(duì)列胸墙,代核心線程執(zhí)行完任務(wù)后我注,從任務(wù)隊(duì)列中取出待處理任務(wù),繼續(xù)處理迟隅。
- 如果線程池中核心線程數(shù)量已經(jīng)飽和但骨,workQueue任務(wù)隊(duì)列中任務(wù)數(shù)也達(dá)到最大值,再來(lái)新任務(wù)智袭,則開啟一個(gè)非核心線程奔缠,進(jìn)行處理任務(wù)。之后非核心線程和核心線程一同處理workQueue任務(wù)隊(duì)列中任務(wù)吼野。
- 如果線程池中核心線程數(shù)量飽和校哎,workQueue任務(wù)隊(duì)列中任務(wù)數(shù)也達(dá)到最大值,非核心線程也達(dá)到最大值瞳步,當(dāng)再來(lái)到新任務(wù)后闷哆,那么線程池就調(diào)用RejectedExecutionHandler的rejectedExecution方法拒絕該任務(wù)。
- 特殊情況单起,如果線程池中無(wú)核心線程抱怔,并且任務(wù)數(shù)不大于任務(wù)隊(duì)列限制,則線程池只開啟一個(gè)非核心線程進(jìn)行處理嘀倒。
調(diào)用策略示例驗(yàn)證
??為了更好的理解調(diào)用策略屈留,采用具體的示例,更清晰明了的進(jìn)行理解测蘑。
package com.bamboolmc.threadpro;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPool {
private static int taskSize = 2;
private static int corePoolSize = 3;
private static int maximumPoolSize = 4;
private static int queueSize = 3;
public static class TestTask implements Runnable{
@Override
public void run() {
if (taskSize>0){
try {
//模擬任務(wù)處理
Thread.sleep(500);
System.out.println(System.currentTimeMillis()+Thread.currentThread().getName()
+" 完成一個(gè)任務(wù)灌危,編號(hào)為t" + (taskSize--));
}catch (Exception e){
e.printStackTrace();
}
}
}
}
public static void main(String args[]) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
1,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(queueSize));
TestTask task;
int size = taskSize;
for (int i = 0; i < size; i++) {
task = new TestTask();
executor.execute(task);
}
executor.shutdown();
}
}
對(duì)比調(diào)用策略1
private static int taskSize = 2;
private static int corePoolSize = 3;
private static int maximumPoolSize = 4;
private static int queueSize = 3;
任務(wù)數(shù)量2,核心線程數(shù)量3
運(yùn)行結(jié)果:
1527001137241pool-1-thread-2 完成一個(gè)任務(wù)碳胳,編號(hào)為t1
1527001137241pool-1-thread-1 完成一個(gè)任務(wù)勇蝙,編號(hào)為t2
對(duì)比調(diào)用策略2
修改如下
private static int taskSize = 5;
private static int corePoolSize = 3;
private static int maximumPoolSize = 4;
private static int queueSize = 3;
任務(wù)數(shù)量5,核心線程數(shù)量3挨约,任務(wù)隊(duì)列3
運(yùn)行結(jié)果:
1527001567366pool-1-thread-2 完成一個(gè)任務(wù)浅蚪,編號(hào)為t4
1527001567366pool-1-thread-1 完成一個(gè)任務(wù)藕帜,編號(hào)為t5
1527001567366pool-1-thread-3 完成一個(gè)任務(wù)烫罩,編號(hào)為t3
1527001567869pool-1-thread-1 完成一個(gè)任務(wù)惜傲,編號(hào)為t1
1527001567869pool-1-thread-2 完成一個(gè)任務(wù),編號(hào)為t2
對(duì)比調(diào)用策略3
修改如下
private static int taskSize = 7;
private static int corePoolSize = 3;
private static int maximumPoolSize = 4;
private static int queueSize = 3;
任務(wù)數(shù)量7, 核心線程數(shù)量3,任務(wù)隊(duì)列3贝攒,非核心線程1
運(yùn)行結(jié)果:
1527002003014pool-1-thread-3 完成一個(gè)任務(wù)盗誊,編號(hào)為t6
1527002003014pool-1-thread-2 完成一個(gè)任務(wù),編號(hào)為t4
1527002003014pool-1-thread-1 完成一個(gè)任務(wù)隘弊,編號(hào)為t7
1527002003014pool-1-thread-4 完成一個(gè)任務(wù)哈踱,編號(hào)為t5
1527002003516pool-1-thread-3 完成一個(gè)任務(wù),編號(hào)為t3
1527002003516pool-1-thread-1 完成一個(gè)任務(wù)梨熙,編號(hào)為t2
1527002003516pool-1-thread-2 完成一個(gè)任務(wù)开镣,編號(hào)為t1
對(duì)比調(diào)用策略4
修改如下
private static int taskSize = 8;
private static int corePoolSize = 3;
private static int maximumPoolSize = 4;
private static int queueSize = 3;
任務(wù)數(shù)量8, 核心線程數(shù)量3,任務(wù)隊(duì)列3,非核心線程1
運(yùn)行結(jié)果:
第8個(gè)任務(wù)運(yùn)行時(shí)咽扇,線程池拒絕邪财,拋出異常
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task com.bamboolmc.threadpro.ThreadPool$TestTask@14ae5a5 rejected from java.util.concurrent.ThreadPoolExecutor@7f31245a[Running, pool size = 4, active threads = 4, queued tasks = 3, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
at com.bamboolmc.threadpro.ThreadPool.main(ThreadPool.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
1527002190243pool-1-thread-3 完成一個(gè)任務(wù),編號(hào)為t8
1527002190243pool-1-thread-1 完成一個(gè)任務(wù)质欲,編號(hào)為t6
1527002190243pool-1-thread-2 完成一個(gè)任務(wù)树埠,編號(hào)為t5
1527002190243pool-1-thread-4 完成一個(gè)任務(wù),編號(hào)為t7
1527002190749pool-1-thread-2 完成一個(gè)任務(wù)嘶伟,編號(hào)為t3
1527002190749pool-1-thread-1 完成一個(gè)任務(wù)怎憋,編號(hào)為t3
1527002190749pool-1-thread-3 完成一個(gè)任務(wù),編號(hào)為t4
對(duì)比調(diào)用策略5
修改如下
private static int taskSize = 3;
private static int corePoolSize = 0;
private static int maximumPoolSize = 4;
private static int queueSize = 3;
任務(wù)數(shù)量3, 核心線程數(shù)量0,任務(wù)隊(duì)列3九昧,非核心線程4
運(yùn)行結(jié)果:
1527002486575pool-1-thread-1 完成一個(gè)任務(wù)绊袋,編號(hào)為t3
1527002487078pool-1-thread-1 完成一個(gè)任務(wù),編號(hào)為t2
1527002487579pool-1-thread-1 完成一個(gè)任務(wù)铸鹰,編號(hào)為t1
線程池分類
根據(jù)構(gòu)建線程池時(shí)傳入的參數(shù)不同癌别,我們?cè)贏ndroid系統(tǒng)中常見(jiàn)有4種不同功能特性的線程池。
- CachedThreadPool
- FixedThreadPool
- SingleThreadExecutor
- ScheduledThreadPool
我們可以用Executors.newXXX的方式去實(shí)例化我們需要的線程池掉奄,如實(shí)例化一個(gè)CachedThreadPool
ExecutorService executorService = Executors.newCachedThreadPool();
CachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
核心線程數(shù):0
最大線程數(shù):2的31次方-1
超時(shí)時(shí)長(zhǎng):60秒
任務(wù)隊(duì)列:SynchronousQueue
??由此可見(jiàn)规个,CachedThreadPool只有非核心線程,并且非核心線程最大數(shù)量可以任意大姓建,當(dāng)前已建線程都在執(zhí)行任務(wù)時(shí)诞仓,再來(lái)新的任務(wù)會(huì)開啟新的線程來(lái)執(zhí)行,閑置線程超過(guò)60秒速兔,就會(huì)被收回墅拭。由于使用了SynchronousQueue隊(duì)列,所有提交的任務(wù)都會(huì)被立即執(zhí)行涣狗。這類線程池比較適合大量的耗時(shí)較少的任務(wù)谍婉。
FixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
核心線程數(shù):固定(新建線程池時(shí)提供的參數(shù))
最大線程數(shù):同核心線程數(shù)
超時(shí)時(shí)長(zhǎng):0
任務(wù)隊(duì)列:LinkedBlockingQueue
??由此可見(jiàn)舒憾,F(xiàn)ixedThreadPool只有固定個(gè)數(shù)的核心線程數(shù),無(wú)非核心線程穗熬,并且核心線程無(wú)超時(shí)限制镀迂,除非線程池關(guān)閉,否則線程即使處于空閑狀態(tài)唤蔗,也不會(huì)被回收探遵,因此能夠更快的響應(yīng)外界請(qǐng)求。另外任務(wù)隊(duì)列容量沒(méi)有大小限制妓柜。當(dāng)所有線程均有任務(wù)執(zhí)行時(shí)箱季,新任務(wù)會(huì)在任務(wù)隊(duì)列排隊(duì),線程執(zhí)行完棍掐,取出任務(wù)隊(duì)列中任務(wù)執(zhí)行藏雏。
SingleThreadExecutor
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
}
核心線程數(shù):1
最大線程數(shù):1
超時(shí)時(shí)長(zhǎng):0
任務(wù)隊(duì)列:LinkedBlockingQueue
??由此可見(jiàn),SingleThreadExecutor只有1個(gè)核心線程作煌,所有任務(wù)都會(huì)在一個(gè)線程中按順序執(zhí)行掘殴;任務(wù)隊(duì)列容量沒(méi)有大小限制;另外如果某些錯(cuò)誤而導(dǎo)致線程終止最疆,則會(huì)創(chuàng)建新的線程繼續(xù)執(zhí)行后續(xù)的任務(wù)(與newFixedThreadPool(1)的不同杯巨,無(wú)法創(chuàng)建新的線程繼續(xù)執(zhí)行后續(xù)任務(wù));由于是在一個(gè)線程執(zhí)行任務(wù)努酸,所以無(wú)需處理線程同步問(wèn)題了服爷。
ScheduledThreadPool
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue());
}
核心線程數(shù):固定
最大線程數(shù):2的31次方-1
超時(shí)時(shí)長(zhǎng):10毫秒
任務(wù)隊(duì)列:DelayedWorkQueue
??由此可見(jiàn),ScheduledThreadPool核心線程數(shù)固定获诈,非核心線程數(shù)無(wú)限大仍源,非核心線程超時(shí)時(shí)長(zhǎng)10毫秒。主要用于執(zhí)行定時(shí)任務(wù)和具有固定周期的任務(wù)舔涎。
使用方法異同
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new TestTask());
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new TestTask());
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(new TestTask());
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
executor.schedule(new TestTask(),2000,TimeUnit.MILLISECONDS);
任務(wù)隊(duì)列BlockingQueue
??阻塞隊(duì)列(BlockingQueue)是一個(gè)支持兩個(gè)附加操作的隊(duì)列笼踩。這兩個(gè)附加的操作支持阻塞的插入和移除方法。
- 支持阻塞的插入方法:意思是當(dāng)隊(duì)列滿時(shí)亡嫌,隊(duì)列會(huì)阻塞插入元素的線程嚎于,直到隊(duì)列不滿時(shí),自動(dòng)喚醒被阻塞線程繼續(xù)執(zhí)行插入操作挟冠。
- 支持阻塞的移除方法:意思是在隊(duì)列為空時(shí)于购,獲取元素的線程會(huì)阻塞,等待隊(duì)列變?yōu)榉强諘r(shí)知染,自動(dòng)喚醒肋僧。
??四種類型線程池分析時(shí),發(fā)現(xiàn)其中的任務(wù)隊(duì)列參數(shù)分別使用到SynchronousQueue、LinkedBlockingQueue嫌吠、DelayedWorkQueue這三種不同的任務(wù)隊(duì)列止潘。除此之外,系統(tǒng)還提供了PriorityBlockingQueue辫诅、ArrayBlockingQueue凭戴,DelayQueue,這些類均實(shí)現(xiàn)自BlockingQueue接口泥栖。
public interface BlockingQueue<E> extends Queue<E> {
boolean add(E e);
boolean offer(E e);
void put(E e) throws InterruptedException;
boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException;
E take() throws InterruptedException;
E poll(long timeout, TimeUnit unit) throws InterruptedException;
int remainingCapacity();
boolean remove(Object o);
public boolean contains(Object o);
int drainTo(Collection<? super E> c);
int drainTo(Collection<? super E> c, int maxElements);
}
BlockingQueue作為一個(gè)接口簇宽,提供了添加、刪除元素方法吧享。
添加方法
- add: 添加元素到隊(duì)列,成功返回true譬嚣;隊(duì)列容量滿了钢颂,再添加元素時(shí),會(huì)拋出IllegalStateException異常拜银。
- offer:添加元素到隊(duì)列殊鞭,成功返回true,失敗返回false
- put:添加指定元素到隊(duì)列尼桶,如果隊(duì)列容量滿了操灿,則會(huì)阻塞到隊(duì)列有空間。
刪除方法
- take:刪除隊(duì)列頭部元素泵督,如果隊(duì)列為空趾盐,則一直阻塞到隊(duì)列有元素為止。返回頭部元素小腊。
- poll:刪除隊(duì)列頭部元素救鲤,在指定時(shí)間內(nèi),如果隊(duì)列不為空秩冈,則刪除頭部元素本缠,并返回頭部元素。在制定時(shí)間內(nèi)隊(duì)列仍為空入问,則返回null丹锹。
- remove:刪除隊(duì)列內(nèi)指定的元素,如果刪除成功則返回true芬失,如果找不到該指定元素楣黍,拋出NullPointerException。
其他方法
- remainingCapacity:返回隊(duì)列能夠添加元素的數(shù)量(阻塞或無(wú)限制除外)麸折。
- contains:隊(duì)列是否包含某指定元素锡凝。
- drainTo:從隊(duì)列中移除(所有或指定數(shù)量的)可用元素,并將它們添加到給定集合中垢啼。
SynchronousQueue
??沒(méi)有元素存儲(chǔ)空間的阻塞隊(duì)列窜锯,如果在插入元素時(shí)后續(xù)沒(méi)有執(zhí)行取出的操作张肾,那么插入的行為就會(huì)被阻塞。構(gòu)造方法如下
public SynchronousQueue()
public SynchronousQueue(boolean fair)
LinkedBlockingQueue
??基于鏈表的阻塞隊(duì)列锚扎,可指定容量吞瞪,默認(rèn)容量無(wú)窮大(2的31次方-1),采用FIFO(first-in-first-out)的訪問(wèn)策略驾孔。
public LinkedBlockingQueue()
public LinkedBlockingQueue(int capacity)
public LinkedBlockingQueue(Collection<? extends E> c)
PriorityBlockingQueue
??基于優(yōu)先級(jí)的阻塞隊(duì)列芍秆,隊(duì)列容量由使用者指定,優(yōu)先級(jí)的高低是如何指定的呢翠勉,可根據(jù)如下的構(gòu)造函數(shù)中看到Comparator<? super E> comparator 就是指定優(yōu)先級(jí)的比較器妖啥。因此隊(duì)列元素(也就是要執(zhí)行的任務(wù))需要實(shí)現(xiàn)Comparator接口,來(lái)定義優(yōu)先級(jí)高低对碌。如果不設(shè)置容量大小的話荆虱,默認(rèn)隊(duì)列容量為11。
public PriorityBlockingQueue()
public PriorityBlockingQueue(int initialCapacity)
public PriorityBlockingQueue(int initialCapacity,Comparator<? super E> comparator)
public PriorityBlockingQueue(Collection<? extends E> c)
ArrayBlockingQueue
??基于數(shù)組的阻塞隊(duì)列朽们,隊(duì)列容量由使用者指定怀读,由于隊(duì)列基于數(shù)組,初始化后骑脱,容量大小就是固定的菜枷。當(dāng)設(shè)定boolean fair為true時(shí),隊(duì)列訪問(wèn)策略為FIFO叁丧;如果不設(shè)定啤誊,則默認(rèn)false,訪問(wèn)策略是無(wú)序的歹袁。
public ArrayBlockingQueue(int capacity)
public ArrayBlockingQueue(int capacity, boolean fair)
public ArrayBlockingQueue(int capacity, boolean fair,Collection<? extends E> c)
其他
詳細(xì)的阻塞隊(duì)列可參考源碼及如下文章學(xué)習(xí)
https://blog.csdn.net/qq_38989725/article/details/73298856