1票渠、構(gòu)造方法
public ThreadPoolExecutor(int corePoolSize, //核心線程數(shù)
int maximumPoolSize, //線程池最大容量
long keepAliveTime, //線程扁殖活時(shí)間,實(shí)現(xiàn)方式是:延時(shí)從任務(wù)隊(duì)列取任務(wù)侮腹。
TimeUnit unit, //背氨蹋活時(shí)間單位
BlockingQueue<Runnable> workQueue, //任務(wù)隊(duì)列
ThreadFactory threadFactory) //創(chuàng)建線程工廠
BlockingQueue<Runnable> workQueue; //任務(wù)隊(duì)列。如果當(dāng)前沒有空閑線程父阻,任務(wù)會存儲到此隊(duì)列愈涩。隊(duì)列由用戶創(chuàng)建望抽,通過構(gòu)造方法傳進(jìn)來。
HashSet<Worker> workers = new HashSet<>(); //工作的線程Set履婉,工作線程和空閑線程都存儲在這里煤篙。
2、 public void execute(Runnable command)方法發(fā)送任務(wù)給線程池毁腿。
- 如果當(dāng)前線程數(shù)沒有達(dá)到最大核心線程數(shù)辑奈,會創(chuàng)建核心線程。
- 否則會把任務(wù)添加進(jìn)任務(wù)隊(duì)列已烤,然后再創(chuàng)建非核心線程鸠窗。
- (創(chuàng)建線程方法addWorker(Runnable firstTask, boolean core),core是線程種類胯究,核心/非核心稍计。是否達(dá)到最大線程數(shù),是在創(chuàng)建過程中判斷的唐片。)
3丙猬、 addWorker(Runnable firstTask, boolean core)
一、 addWorker創(chuàng)建一個(gè)工作線程是通過創(chuàng)建一個(gè)包含一個(gè)Thread的Worker類费韭。
二茧球、 Worker本身繼承了Runnable接口,包含run()方法星持。把自己傳入自己包含的Thread變量中執(zhí)行抢埋。
三、 addWorker中有調(diào)用了worker.thread.start(), 就在新的線程中執(zhí)行了其包含的Runnable(worker),調(diào)用了worker的run()方法督暂,中的runWorker()揪垄,方法。
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable {
...
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
public void run() {
runWorker(this);
}
...
}
4逻翁、 runWorker(Worker w)方法已經(jīng)在新的線程中運(yùn)行饥努。
新線程中通過while循環(huán)執(zhí)行task,Worker中的task不為空就執(zhí)行八回,如果Worker中的task為空酷愧,就通過getTask()方法取任務(wù)隊(duì)列中的任務(wù)。
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
try {
while (task != null || (task = getTask()) != null) {
...
}
5缠诅、 Runnable getTask()獲取任務(wù)隊(duì)列中的任務(wù)溶浴。
線程保活時(shí)間也是從這里完成的管引。延時(shí)的從任務(wù)隊(duì)列中取任務(wù)士败,如果延時(shí)后取出為null,線程結(jié)束褥伴。如果取出了谅将,就繼續(xù)在當(dāng)前線程中執(zhí)行Runnable任務(wù)漾狼。也完成了,線程池的復(fù)用和任務(wù)隊(duì)列的順序執(zhí)行戏自。
private Runnable getTask() {
for (;;) {
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;