線程池實現原理
1.線程池簡介
爲什麼要構建線程池?
1.複用已有的資源(減少cpu時間片的切換)
2.控制現場資源總數
優勢:
1.限流->控制線程數量
2.降低頻繁創建和銷燬線程。(對於任務的響應速度更快,可以直接從線程池中取,不需要創建線程)
2.Java中提供的線程池
Executors,線程池工具類 。
//主要都是ThreadPoolExecutor 構造的線程池
//ThreadPoolExecutor的構造方法
public ThreadPoolExecutor(int corePoolSize,//核心線程數
int maximumPoolSize,最大線程數
long keepAliveTime,//保持連接時間
TimeUnit unit,//保持連接時間單位
BlockingQueue<Runnable> workQueue,//阻塞隊列
ThreadFactory threadFactory,//線程工廠
RejectedExecutionHandler handler) //拒絕策略
newFixedThreadPool()
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
newSingleThreadScheduledExecutor
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}
newScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
newWorkStealingPool
public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool
(parallelism,
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}
//ForkJoinPool構造方法。
public ForkJoinPool(int parallelism,
ForkJoinWorkerThreadFactory factory,
UncaughtExceptionHandler handler,
boolean asyncMode) {
this(checkParallelism(parallelism),
checkFactory(factory),
handler,
asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
"ForkJoinPool-" + nextPoolId() + "-worker-");
checkPermission();
}
問題1:猜想keepAliveTime如何去監控線程進行回收?下面我們看看線程池是如何實現的。
1.有一個是否回收核心線程的開關(allowCoreThreadTimeOut)
2.當前線程數是否大於核心線程數(wc > corePoolSize)
請參考getTask()方法,只要返回空,線程則會進行回收。
3.ThreadPoolExecutor實現原理:
execute方法實現如下:
//線程默認運行狀態是 RUNNING
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3;
//表示低29位全是1,高3位爲0
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
// runState is stored in the high-order bits
//高3位存儲線程運行狀態
private static final int RUNNING = -1 << COUNT_BITS;
private static final int SHUTDOWN = 0 << COUNT_BITS;
private static final int STOP = 1 << COUNT_BITS;
private static final int TIDYING = 2 << COUNT_BITS;
private static final int TERMINATED = 3 << COUNT_BITS;
// Packing and unpacking ctl
//獲取高三位,表示獲取線程運行狀態
private static int runStateOf(int c) { return c & ~CAPACITY; }
//獲取低29位,表示獲取線程數量
private static int workerCountOf(int c) { return c & CAPACITY; }
private static int ctlOf(int rs, int wc) { return rs | wc; }
//ThreadPoolExecutor.execute實現源碼
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps://分爲3步
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
//ctl默認狀態爲運行狀態
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
addWorker:
//firstTask 傳遞的是.execute(Runnable r) 中的r,core 表示是否創建一個核心線程數
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
主要做兩件事:
//主要增加工作線程數
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
//最主要做的事情 CAS給ctl加1,增加一個工作線程數
if (compareAndIncrementWorkerCount(c))
break retry;
//重試獲取,再一次讀區ctl
c = ctl.get(); // Re-read ctl
//如果當前狀態不是之前的狀態,則繼續retry
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
//主要創建一個Worker線程,並添加到隊列(真正意義的構建線程)
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);
/**
*Worker(Runnable firstTask) {
* 初始化state爲-1。
* setState(-1); // inhibit interrupts until runWorker
* this.firstTask = firstTask;
* 把當前Worker對象賦值爲Worker中的thread
* this.thread = getThreadFactory().newThread(this);
*}
*
*/
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
//當前狀態爲Runnable 或者(狀態爲SHUTDOWN,firstTask爲null)
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
//private final HashSet<Worker> workers = new HashSet<Worker>();
//把當前worker添加到workers Set中
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
/**
* public void run() {
* runWorker(this);
* }
*
*/
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
//如果執行失敗,需要回滾
/**
* private void addWorkerFailed(Worker w) {
* final ReentrantLock mainLock = this.mainLock;
* mainLock.lock();
* try {
* if (w != null)
* workers.remove(w);
* //把數量減1 CAS實現
* decrementWorkerCount();
* tryTerminate();
* } finally {
* mainLock.unlock();
* }
* }
*/
addWorkerFailed(w);
}
return workerStarted;
//runWorker 是核心
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {方法後面講
//getTask是從阻塞隊列裏獲取,已經不是直接交給核心線程了。
while (task != null || (task = getTask()) != null) {
//不僅僅是加鎖着麼簡單!後面講解
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
//問題2.爲什麼要調用run方法呢?
//task這時候已經存在線程池中了,所以沒有必要.start方法,再創建一個線程去執行了
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
Worker:實現了Runnable,並且繼承了AQS
問題3:Worker爲什麼要實現AQS呢?爲什麼不用ReentrantLock實現呢?
我們看一下Worker裏面做了什麼?
Worker(Runnable firstTask) {
//設置同步狀態,
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
protected boolean tryAcquire(int unused) {
//1是表示獲取鎖,0表示釋放狀態,-1是初始化狀態
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
protected boolean tryRelease(int unused) {
setExclusiveOwnerThread(null);
setState(0);
return true;
}
//上面的runWorker 爲什麼w要加鎖呢?
//ThreadPoolExecutor.shutdown方法
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
advanceRunState(SHUTDOWN);
interruptIdleWorkers();
onShutdown(); // hook for ScheduledThreadPoolExecutor
} finally {
mainLock.unlock();
}
tryTerminate();
}
//interruptIdleWorkers方法,中斷時會判斷,線程是否還在運行。
private void interruptIdleWorkers(boolean onlyOne) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (Worker w : workers) {
Thread t = w.thread;
if (!t.isInterrupted() && /*重點*/ w.tryLock()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
} finally {
w.unlock();
}
}
if (onlyOne)
break;
}
} finally {
mainLock.unlock();
}
}
這就是爲什麼Worker要實現AQS的原因,爲了shuatdown時不終止正在運行的任務
//getTask從workQueue獲取執行的線程,非核心線程數是否被回收?
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
執行流程:
圖例:
隊列的簡單操作
offer 添加一個元素並返回true 如果隊列已滿,則返回false
poll 移除並返問隊列頭部的元素 如果隊列爲空,則返回null
put 添加一個元素 如果隊列滿,則阻塞
take 移除並返回隊列頭部的元素 如果隊列爲空,則阻塞
1.不建議使用Executors 創建線程
2.線程的執行情況->
IO密集型 CPU核心數的2倍
CPU密集型 CPU核心數+1
Executor框架最核心的接口是Executor,它表示任務的執行器。
Executor的子接口爲ExecutorService。
ExecutorService有兩大實現類:ThreadPoolExecutor和ScheduledThreadPoolExecutor。
注:本文爲博主原創文章,轉載請附上原文出處鏈接和本聲明。