常用線程池
1、newSingleThreadExecutor
創(chuàng)建一個(gè)單線程化的線程池,它只會(huì)用唯一的工作線程來(lái)執(zhí)行任務(wù),保證所有任務(wù)按照指定順序(FIFO, LIFO, 優(yōu)先級(jí))執(zhí)行。
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
2、newFixedThreadPool
創(chuàng)建一個(gè)定長(zhǎng)線程池,可控制線程最大并發(fā)數(shù),超出的線程會(huì)在隊(duì)列中等待。
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
3、newCachedThreadPool
創(chuàng)建一個(gè)可緩存線程池,如果線程池長(zhǎng)度超過(guò)處理需要,可靈活回收空閑線程,若無(wú)可回收,則新建線程。
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
4、newScheduledThreadPool
創(chuàng)建一個(gè)定長(zhǎng)線程池,支持定時(shí)及周期性任務(wù)執(zhí)行。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }
Executors各個(gè)方法的弊端
newFixedThreadPool、newSingleThreadExecutor:
主要問(wèn)題是堆積的請(qǐng)求處理隊(duì)列可能會(huì)耗費(fèi)非常大的內(nèi)存,甚至OOM。
newCachedThreadPool、newScheduledThreadPool:
主要問(wèn)題是線程數(shù)最大數(shù)是Integer.MAX_VALUE,可能會(huì)創(chuàng)建數(shù)量非常多的線程,甚至OOM。
線程池的作用
1、提高效率 創(chuàng)建好一定數(shù)量的線程放在池中,等需要使用的時(shí)候就從池中拿一個(gè),這要比需要的時(shí)候創(chuàng)建一個(gè)線程對(duì)象要快的多。
2、方便管理 可以編寫線程池管理代碼對(duì)池中的線程同一進(jìn)行管理,比如說(shuō)啟動(dòng)時(shí)有該程序創(chuàng)建100個(gè)線程,每當(dāng)有請(qǐng)求的時(shí)候,就分配一個(gè)線程去工作,如果剛好并發(fā)有101個(gè)請(qǐng)求,那多出的這一個(gè)請(qǐng)求可以排隊(duì)等候,避免因無(wú)休止的創(chuàng)建線程導(dǎo)致系統(tǒng)崩潰。