1)重用執行緒,避免系統頻繁地建立和銷毀執行緒
2)任務過多時,通過排隊避免建立過多執行緒,減少系統資源的消耗
阿里開發手冊中規定:執行緒資源必須通過執行緒池提供,不允許在應用中自行顯式建立執行緒。
jdk中線程池的實現類是threadpoolexecutor,先來看看其最重要的構造方法:
引數public threadpoolexecutor(int corepoolsize,
int maximumpoolsize,
long keepalivetime,
timeunit unit,
blockingqueueworkqueue,
threadfactory threadfactory,
rejectedexecutionhandler handler)
描述corepoolsize
核心執行緒數
maximumpoolsize
最大執行緒數
keepalivetime
執行緒池中線程的數量超過corepoolsize時,多餘的空閒執行緒的存活時間
unit
keepalivetime的單位
workqueue
任務佇列
threadfactory
執行緒工廠
handler
拒絕策略
threadpoolexecutor類核心方法execute如下:
核心**為:public void execute(runnable command)
if (isrunning(c) && workqueue.offer(command))
else if (!addworker(command, false))
reject(command);
}
executor框架提供了各種型別的執行緒池,其內部都是通過threadpoolexecutor來實現的,主要有以下工廠方法:
下面來一一描述上述工廠方法:public static executorservice newfixedthreadpool(int nthreads)
public static executorservice newsinglethreadexecutor()
public static executorservice newcachedthreadpool()
public static scheduledexecutorservice newsinglethreadscheduledexecutor()
public static scheduledexecutorservice newscheduledthreadpool(int corepoolsize)
public static executorservice newfixedthreadpool(int nthreads)
public static executorservice newsinglethreadexecutor()
public static executorservice newcachedthreadpool()
public static scheduledexecutorservice newsinglethreadscheduledexecutor()
public scheduledthreadpoolexecutor(int corepoolsize)
阿里開發手冊中規定:執行緒池不允許使用executors去建立,而是通過threadpoolexecutor的方式,這樣的處理方式讓寫的同學更加明確執行緒池的執行規則,避免資源耗盡的風險。public static scheduledexecutorservice newscheduledthreadpool(int corepoolsize)
public scheduledthreadpoolexecutor(int corepoolsize)
executors返回的執行緒池物件的弊端如下:
fixedthreadpool和singlethreadpool:
允許的請求佇列長度為integer.max_value,可能會堆積大量的請求,從而導致oom。
cachedthreadpool和scheduledthreadpool:
允許建立的執行緒數量為integer.max_value,可能會建立大量的執行緒,從而導致oom。
執行緒池 基礎
概念 乙個執行緒的宣告週期中包含了三個時間段,1是建立執行緒的時間 t1,2是執行緒執行任務所要花費的時間 t2,3是執行緒銷毀的時間 t3,執行緒池主要技術點就是縮短或調整t1和t3的時間,從而提高伺服器的效能。因為它把t1和t3安排在程式啟動或者伺服器空閒的時間段中,這樣就不會有t1和t3的開銷...
執行緒池基礎
1 重用執行緒,避免執行緒建立和消耗帶來的效能消耗 2 控制線程池的最大併發數,避免執行緒之間搶系統資源而導致的阻塞現象。3 對執行緒管理,提供定時執行等功能。1 executor介面 public inte ce executor將任務提交和執行解耦,引數傳入runnable 任務 通過execu...
Synchronized 和執行緒池篇
corepoolsize n maximumpoolsize n keepalivetime 0l workqueue linkedblockqueue 特點為固定執行緒池大小,缺點執行緒較多的時候會導致佇列等待執行緒較多,造成oom corepoolsize 0 maximumpoolsize i...