Executors創(chuàng)建的4種線程池的使用

一、newCachedThreadPool

創(chuàng)建一個(gè)可緩存線程池陆赋,如果線程池長(zhǎng)度超過(guò)處理需要,可靈活回收空閑線程嚷闭,若無(wú)可回收攒岛,則新建線程。

 /**
     * Creates a thread pool that creates new threads as needed, but
     * will reuse previously constructed threads when they are
     * available.  These pools will typically improve the performance
     * of programs that execute many short-lived asynchronous tasks.
     * Calls to {@code execute} will reuse previously constructed
     * threads if available. If no existing thread is available, a new
     * thread will be created and added to the pool. Threads that have
     * not been used for sixty seconds are terminated and removed from
     * the cache. Thus, a pool that remains idle for long enough will
     * not consume any resources. Note that pools with similar
     * properties but different details (for example, timeout parameters)
     * may be created using {@link ThreadPoolExecutor} constructors.
     *
     * @return the newly created thread pool
     */
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
  1. corePoolSize = 0
  2. maximumPoolSize = Integer.MAX_VALUE

SynchronousQueue是一個(gè)只有1個(gè)元素的隊(duì)列胞锰,入隊(duì)的任務(wù)需要一直等待直到隊(duì)列中的元素被移出灾锯。核心線程數(shù)是0,意味著所有任務(wù)會(huì)先入隊(duì)列嗅榕;最大線程數(shù)是Integer.MAX_VALUE顺饮,可以認(rèn)為線程數(shù)量是沒(méi)有限制的。KeepAlive時(shí)間被設(shè)置成60秒凌那,意味著在沒(méi)有任務(wù)的時(shí)候線程等待60秒以后退出兼雄。CachedThreadPool對(duì)任務(wù)的處理策略是提交的任務(wù)會(huì)立即分配一個(gè)線程進(jìn)行執(zhí)行,線程池中線程數(shù)量會(huì)隨著任務(wù)數(shù)的變化自動(dòng)擴(kuò)張和縮減帽蝶,在任務(wù)執(zhí)行時(shí)間無(wú)限延長(zhǎng)的極端情況下會(huì)創(chuàng)建過(guò)多的線程赦肋。

二、newFixedThreadPool

創(chuàng)建一個(gè)定長(zhǎng)線程池励稳,可控制線程最大并發(fā)數(shù)佃乘,超出的線程會(huì)在隊(duì)列中等待。

    /**
     * Creates a thread pool that reuses a fixed number of threads
     * operating off a shared unbounded queue.  At any point, at most
     * {@code nThreads} threads will be active processing tasks.
     * If additional tasks are submitted when all threads are active,
     * they will wait in the queue until a thread is available.
     * If any thread terminates due to a failure during execution
     * prior to shutdown, a new one will take its place if needed to
     * execute subsequent tasks.  The threads in the pool will exist
     * until it is explicitly {@link ExecutorService#shutdown shutdown}.
     *
     * @param nThreads the number of threads in the pool
     * @return the newly created thread pool
     * @throws IllegalArgumentException if {@code nThreads <= 0}
     */
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
  1. corePoolSize == maximumPoolSize
  2. new LinkedBlockingQueue<Runnable>() 【 DefaltCapacity = Integer.MAX_VALUE】

FixedThreadPool的優(yōu)點(diǎn)是能夠保證所有的任務(wù)都被執(zhí)行驹尼,永遠(yuǎn)不會(huì)拒絕新的任務(wù)趣避;同時(shí)缺點(diǎn)是隊(duì)列數(shù)量沒(méi)有限制,在任務(wù)執(zhí)行時(shí)間無(wú)限延長(zhǎng)的這種極端情況下會(huì)造成內(nèi)存問(wèn)題新翎。

三程帕、newSingleThreadExecutor

創(chuàng)建一個(gè)單線程化的線程池,它只會(huì)用唯一的工作線程來(lái)執(zhí)行任務(wù)地啰,保證所有任務(wù)按照指定順序(FIFO, LIFO, 優(yōu)先級(jí))執(zhí)行骆捧。

 /**
     * Creates an Executor that uses a single worker thread operating
     * off an unbounded queue. (Note however that if this single
     * thread terminates due to a failure during execution prior to
     * shutdown, a new one will take its place if needed to execute
     * subsequent tasks.)  Tasks are guaranteed to execute
     * sequentially, and no more than one task will be active at any
     * given time. Unlike the otherwise equivalent
     * {@code newFixedThreadPool(1)} the returned executor is
     * guaranteed not to be reconfigurable to use additional threads.
     *
     * @return the newly created single-threaded Executor
     */
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
  1. corePoolSize = 1
  2. maximumPoolSize = 1
  3. new LinkedBlockingQueue<Runnable>() 【 DefaltCapacity = Integer.MAX_VALUE】

這個(gè)工廠方法中使用無(wú)界LinkedBlockingQueue,并的將線程數(shù)設(shè)置成1髓绽,除此以外還使用FinalizableDelegatedExecutorService類進(jìn)行了包裝敛苇。這個(gè)包裝類的主要目的是為了屏蔽ThreadPoolExecutor中動(dòng)態(tài)修改線程數(shù)量的功能,僅保留ExecutorService中提供的方法。雖然是單線程處理枫攀,一旦線程因?yàn)樘幚懋惓5仍蚪K止的時(shí)候括饶,ThreadPoolExecutor會(huì)自動(dòng)創(chuàng)建一個(gè)新的線程繼續(xù)進(jìn)行工作。

四来涨、newScheduledThreadPool

創(chuàng)建一個(gè)定長(zhǎng)線程池图焰,支持定時(shí)及周期性任務(wù)執(zhí)行。

/**
     * Creates a thread pool that can schedule commands to run after a
     * given delay, or to execute periodically.
     * @param corePoolSize the number of threads to keep in the pool,
     * even if they are idle
     * @return a newly created scheduled thread pool
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
     */
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末蹦掐,一起剝皮案震驚了整個(gè)濱河市技羔,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌卧抗,老刑警劉巖藤滥,帶你破解...
    沈念sama閱讀 218,204評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件咐蚯,死亡現(xiàn)場(chǎng)離奇詭異困食,居然都是意外死亡灼芭,警方通過(guò)查閱死者的電腦和手機(jī)粉楚,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門馁痴,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)收擦,“玉大人哆键,你說(shuō)我怎么就攤上這事苞轿∈雀担” “怎么了金句?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,548評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)吕嘀。 經(jīng)常有香客問(wèn)我趴梢,道長(zhǎng),這世上最難降的妖魔是什么币他? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,657評(píng)論 1 293
  • 正文 為了忘掉前任坞靶,我火速辦了婚禮,結(jié)果婚禮上蝴悉,老公的妹妹穿的比我還像新娘彰阴。我一直安慰自己,他們只是感情好拍冠,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布尿这。 她就那樣靜靜地躺著,像睡著了一般庆杜。 火紅的嫁衣襯著肌膚如雪射众。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,554評(píng)論 1 305
  • 那天晃财,我揣著相機(jī)與錄音叨橱,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛罗洗,可吹牛的內(nèi)容都是我干的愉舔。 我是一名探鬼主播,決...
    沈念sama閱讀 40,302評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼伙菜,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼轩缤!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起贩绕,我...
    開(kāi)封第一講書(shū)人閱讀 39,216評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤火的,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后淑倾,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體馏鹤,經(jīng)...
    沈念sama閱讀 45,661評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評(píng)論 3 336
  • 正文 我和宋清朗相戀三年踊淳,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片陕靠。...
    茶點(diǎn)故事閱讀 39,977評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡迂尝,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出剪芥,到底是詐尸還是另有隱情垄开,我是刑警寧澤,帶...
    沈念sama閱讀 35,697評(píng)論 5 347
  • 正文 年R本政府宣布税肪,位于F島的核電站溉躲,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏益兄。R本人自食惡果不足惜锻梳,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望净捅。 院中可真熱鬧疑枯,春花似錦、人聲如沸蛔六。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,898評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)国章。三九已至具钥,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間液兽,已是汗流浹背骂删。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,019評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人桃漾。 一個(gè)月前我還...
    沈念sama閱讀 48,138評(píng)論 3 370
  • 正文 我出身青樓坏匪,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親撬统。 傳聞我的和親對(duì)象是個(gè)殘疾皇子适滓,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評(píng)論 2 355