這篇文章主要講解了“線程池ThreadPoolExecutor有什么作用”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“線程池ThreadPoolExecutor有什么作用”吧!

創(chuàng)新互聯(lián)專注于岳塘網(wǎng)站建設服務及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗。 熱誠為您提供岳塘營銷型網(wǎng)站建設,岳塘網(wǎng)站制作、岳塘網(wǎng)頁設計、岳塘網(wǎng)站官網(wǎng)定制、小程序開發(fā)服務,打造岳塘網(wǎng)絡公司原創(chuàng)品牌,更為您提供岳塘網(wǎng)站排名全網(wǎng)營銷落地服務。
一、初始化線程池(4種):
1、newFixedThreadPool()
public final static ExecutorService esPool = Execustor.newFixedThreadPool(50);
特點:corePoolSize == maxPoolSize,使用LinkedBlockingQueue作為堵塞隊列;沒有可執(zhí)行任務時不會釋放線程池;
2、newCachedThreadPool()
public final static ExecutorService esPool = Execustor.newCachedThreadPool();
特點:默認緩存60s,線程數(shù)可以達到Integer.MAX_VALUE,內(nèi)部使用SynchronousQueue作為堵塞隊列;沒有可執(zhí)行任務時,達到keepAliveTime會釋放線程資源,新任務沒有執(zhí)行空閑線程就得重新創(chuàng)建新的線程,會導致系統(tǒng)開銷;使用時,注意控制并發(fā)數(shù),減少創(chuàng)建新線程數(shù);
3、newScheduleThreadPool()
public final static ExecutorService esPool = Execustor.newScheduleThreadPool(50);
特點:指定時間內(nèi)周期性內(nèi)執(zhí)行所提交的任務,一般用于定時同步數(shù)據(jù);
4、newSingleThreadExecutor()
特點:初始化只有一個線程的線程池;內(nèi)部使用LinkedBlockingQueue作為堵塞隊列;
二、源碼實現(xiàn):
1、ThreadPoolExecutor構(gòu)造器
public ThreadPoolExecutor(
int corePoolSize,//核心線程數(shù)
int maximumPoolSize,//最大線程數(shù)
long keepAliveTime,//線程存活時間(必須在線程數(shù)在corePoolSize與maximumPoolSie之間時,存活時間才能生效)
TimeUnit unit,//存活時間的單位
BlockingQueue<Runnable> workQueue,//堵塞隊列
RejectedExecutionHandler handler//當拒絕處理任務時的策略
) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}說明:堵塞隊列BlockingQueue:1)ArrayBlockingQueue(數(shù)組結(jié)構(gòu)的界限堵塞隊列,F(xiàn)IFO);2)LinkedBlockQueue(鏈表結(jié)構(gòu)的堵塞隊列,F(xiàn)IFO);3)SynchronousQueue(不存儲元素的堵塞隊列,每次插入必須等到另一個線程移除);4)PriorityBlockingQueue(具有優(yōu)先級的堵塞隊列)。
拒絕處理任務的策略RejectedExecutionHandler:1)、ThreadPoolExecutor.AbortPolicy(拋棄當前線程,并拋出RejectedExecutionException異常)2)、ThreadPoolExecutor.DiscardPolicy(拋棄當前線程,不拋出異常);3)、ThreadPoolExecutor.DiscardOldestPolicy(拋棄最前面的任務,然后重新嘗試此執(zhí)行過程);4)、CallerRunnsPolicy(調(diào)用線程執(zhí)行此任務)
2、execute()
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
//獲取當前線程的數(shù)量:workerCountOf()
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))//當當前線程數(shù)量小于corePoolSize時,就addWorker
return;
c = ctl.get();
}
//如果當前線程處于Running狀態(tài);
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);
}
//如果當前線程處于非Running狀態(tài);
else if (!addWorker(command, false))
reject(command);
}3、reject()
final void reject(Runnable command) {
handler.rejectedExecution(command, this);
}4、submit()
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
//封裝成一個FutureTask對象,F(xiàn)utureTask類實現(xiàn)Runnable接口
RunnableFuture<T> ftask = newTaskFor(task);
//執(zhí)行execute(),通過execute提交到FutureTask線程池中等待被執(zhí)行,最終執(zhí)行FutureTask的run方法
execute(ftask);
return ftask;
}
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}5、線程狀態(tài)
private static final int COUNT_BITS = Integer.SIZE - 3; //即高3位為111,該狀態(tài)的線程池會接收新任務,并處理阻塞隊列中的任務; private static final int RUNNING = -1 << COUNT_BITS; //即高3位為000,該狀態(tài)的線程池不會接收新任務,但會處理阻塞隊列中的任務; private static final int SHUTDOWN = 0 << COUNT_BITS; //即高3位為001,該狀態(tài)的線程不會接收新任務,也不會處理阻塞隊列中的任務,而且會中斷正在運行的任務; private static final int STOP = 1 << COUNT_BITS; //即高3位為010,該狀態(tài)表示線程池對線程進行整理優(yōu)化; private static final int TIDYING = 2 << COUNT_BITS; //即高3位為011,該狀態(tài)表示線程池停止工作; private static final int TERMINATED = 3 << COUNT_BITS;
6、runWorker()(真正執(zhí)行任務的接口)
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
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 {
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);
}
}
protected void afterExecute(Runnable r, Throwable t) { }感謝各位的閱讀,以上就是“線程池ThreadPoolExecutor有什么作用”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對線程池ThreadPoolExecutor有什么作用這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關知識點的文章,歡迎關注!
網(wǎng)站欄目:線程池ThreadPoolExecutor有什么作用
標題路徑:http://chinadenli.net/article38/gsgdpp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站營銷、網(wǎng)站設計、網(wǎng)站維護、、商城網(wǎng)站、外貿(mào)網(wǎng)站建設
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)