一:線程池的特點
1.復(fù)用線程池中的線程,避免線程的重復(fù)創(chuàng)建和銷毀而造成性能的過度消耗。
2.有效的控制線程池的最大并發(fā)數(shù)棒掠,避免對CPU的資源搶奪而造成阻塞者祖。
3.對線程進行簡單的管理立莉,比如定時執(zhí)行和按一定的時間間隔循環(huán)執(zhí)行。
二:線程池的創(chuàng)建跟銷毀
1.execute和submit都是把線程提交到線程池當中七问,但是execute是沒有返回值的void蜓耻,在exetuor中。submit返回有計算結(jié)果的Furture對象械巡,在executeService中刹淌。
2.shutdown和shutdownNow是銷毀線程池的方法。shutdown()方法只會中斷空閑的線程,但是不會影響到已經(jīng)存入隊列的任務(wù),如果需要停止線程池的運行,可以使用awaitTermination()方法.
三:線程池的分類
1.FixedThreadPool
//特點:
//核心線程數(shù)和最大線程數(shù)相同.
//無超時時間
public static ExecutorService newFixedThreadPool(int nThreads) {
? ? ? ? return new ThreadPoolExecutor(
? ? ? ? ? ? ? ? nThreads, nThreads,
? ? ? ? ? ? ? ? 0L, TimeUnit.SECONDS,
? ? ? ? ? ? ? ? new LinkedBlockingQueue()
? ? ? ? );
這是一種數(shù)量固定的線程池,當線程處于空閑的時候,并不會被回收,除非線程池被關(guān)閉.
當所有的線程都處于活動狀態(tài)時,新任務(wù)都會處于等待狀態(tài),直到有線程空閑出來.
2.CacheThreadPool
//無核心線程,并且最大線程數(shù)為int的最大值.
//超時時間為60s
//隊列為SynchronousQueue同步阻塞隊列,隊列中沒有任何容量.只有在有需求的情況下,隊列中才可以試著添加任務(wù).
public static ExecutorService newCacheThreadPool(){
? ? ? ? return? new ThreadPoolExecutor(
? ? ? ? ? ? ? ? 0,Integer.MAX_VALUE,
? ? ? ? ? ? ? ? 60L,TimeUnit.SECONDS,
? ? ? ? ? ? ? ? new SynchronousQueue()
? ? ? ? );
? ? }
(1)比較適合執(zhí)行大量的耗時較少的任務(wù).
(2)當整個線程都處于閑置狀態(tài)時,線程池中的線程都會超時而被停止,這時候的CacheThreadPool幾乎不占任何系統(tǒng)資源的.
3.ScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSzie) {
? ? ? ? return new ScheduledThreadPoolExecutor(corePoolSzie);
? ? }
//核心線程數(shù)是固定的,非核心線程無限大,并且非核心線程數(shù)有10s的空閑存活時間? ? public ScheduledThreadPoolExecutor(int corePoolSize) {
? ? ? ? super(corePoolSize, Integer.MAX_VALUE,
? ? ? ? ? ? ? ? DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
? ? ? ? ? ? ? ? new DelayedWorkQueue());
? ? }
它的核心線程數(shù)量是固定的,而非核心線程數(shù)是沒有限制的,并且當非核心線程閑置時會被立即回收.
ScheduThreadPool這類線程池主要用于執(zhí)行定時任務(wù)和具有固定周期的重復(fù)任務(wù).
4.SingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
? ? ? ? return Executors.newSingleThreadExecutor();
? ? }
? ? //特點:? ? //線程中只有一個核心線程? ? //并且無超時時間? ? public static ExecutorService newSingleThreadExecutor() {
? ? ? ? return new FinalizableDelegatedExecutorService
? ? ? ? ? ? ? ? (new ThreadPoolExecutor(1, 1,
? ? ? ? ? ? ? ? ? ? ? ? 0L, TimeUnit.MILLISECONDS,
? ? ? ? ? ? ? ? ? ? ? ? new LinkedBlockingQueue()));
? ? }
這類線程池內(nèi)部只有一個核心線程,它確保所有的任務(wù)都在同一個線程中按順序執(zhí)行.