Executor 框架

Executor 框架結(jié)構(gòu)

  • Executor 框架主要由 3 大部分組成如下。
    • 任務(wù)芯侥。包括被執(zhí)行任務(wù)需要實(shí)現(xiàn)的接口:Runnable 接口Callable 接口泊交。
    • 任務(wù)的執(zhí)行。包括任務(wù)執(zhí)行機(jī)制的核心接口 Executor柱查,以及繼承自Executor 的 ExecutorService 接 口廓俭。Executor 框 架 有 兩 個(gè) 關(guān) 鍵 類 實(shí)現(xiàn) 了 ExecutorService 接 口(ThreadPoolExecutorScheduledThreadPoolExecutor)。
    • 異步計(jì)算的結(jié)果唉工。包括接口 Future實(shí)現(xiàn) Future 接口的 FutureTask 類研乒。
    • Executor 框架的使用示意圖

Executor 框架的成員

  • Executor 框架的主要成員:ThreadPoolExecutor、ScheduledThreadPoolExecutor淋硝、Future 接口告嘲、Runnable 接口、Callable 接口和 Executors奖地。

    • (1)ThreadPoolExecutor:

      • ThreadPoolExecutor 通常使用工廠類 Executors 來(lái)創(chuàng)建橄唬。Executors 可以創(chuàng)建 3 種類型的ThreadPoolExecutor:SingleThreadExecutor、FixedThreadPool 和 CachedThreadPool参歹。

      • FixedThreadPool:固定數(shù)量的線程池仰楚,Executors 的 newFixedThreadPool 方法提供兩個(gè)API

        • public static ExecutorService newFixedThreadPool(int nThreads) {
            return new ThreadPoolExecutor(nThreads, nThreads,
                                          0L, TimeUnit.MILLISECONDS,
                                          new LinkedBlockingQueue<Runnable>());
          }
          
          public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
            return new ThreadPoolExecutor(nThreads, nThreads,
                                          0L, TimeUnit.MILLISECONDS,
                                          new LinkedBlockingQueue<Runnable>(),
                                          threadFactory);
          }
          
        • FixedThreadPool 適用于為了滿足資源管理的需求,而需要限制當(dāng)前線程數(shù)量的應(yīng)用場(chǎng)景,它適用于負(fù)載比較重的服務(wù)器

        • FixedThreadPool 的 corePoolSize 和 maximumPoolSize 都被設(shè)置為創(chuàng)建是的指定參數(shù) nThreads

          • 當(dāng)線程池中的線程數(shù)大于 corePoolSize 時(shí)僧界, keepAliveTime 為多余的空閑線程等待新任務(wù)的最長(zhǎng)時(shí)間侨嘀,超過(guò)時(shí)間多余的空閑線程將被終止。這里的 keepAliveTime 為0L捂襟,意味著多余的空閑線程會(huì)被立即終止
          • 如果線程數(shù)少于 corePoolSize 咬腕,則創(chuàng)建新的線程來(lái)執(zhí)行任務(wù)(不管有沒(méi)有空閑的線程,都會(huì)創(chuàng)建)
          • 線程池完成預(yù)熱之后(當(dāng)前運(yùn)行的線程等于corePoolSize )將任務(wù)加入 LinkedBlockingQueue
        • FixedThreadPool 使用無(wú)界隊(duì)列 LinkedBlockingQueue (隊(duì)列容量為Integer.MAX_VALUE)對(duì)線程池帶來(lái)的影響葬荷。

          • 1)線程池線程數(shù)量到達(dá) corePoolSize 后涨共,新任務(wù)將在無(wú)界隊(duì)列中等待,因此線程池的數(shù)量不會(huì)超過(guò)corePoolSize

          • 2)由1)宠漩,使用無(wú)界隊(duì)列時(shí) maximumPoolSize 將是無(wú)效參數(shù)

          • 3)由于1)举反、2),使用無(wú)界隊(duì)列時(shí) keepAliveTime 將是一個(gè)無(wú)效參數(shù)扒吁。(無(wú)界隊(duì)列不會(huì)滿火鼻,將也不會(huì)出現(xiàn)已經(jīng)創(chuàng)建的線程小于最大線程數(shù),所以也不會(huì)有空閑線程 )

          • 4)由于使用無(wú)界隊(duì)列雕崩,所以運(yùn)行中的 FixedThreadPool (未執(zhí)行兩個(gè) shutdown 方法)不會(huì)拒接任務(wù)(不會(huì)調(diào)用RejectedExecutionHandler.rejectedExecution 方法)

            ?

      • SingleThreadExecutor:?jiǎn)蝹€(gè)線程的線程池魁索,Executors 的 newSingleThreadExecutor 方法提供了兩個(gè)API

        • public static ExecutorService newSingleThreadExecutor() {
            return new FinalizableDelegatedExecutorService
              (new ThreadPoolExecutor(1, 1,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>()));
          }
          
          public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
            return new FinalizableDelegatedExecutorService
              (new ThreadPoolExecutor(1, 1,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory));
          }
          
        • SingleThreadExecutor 適用于需要保證順序地執(zhí)行各個(gè)任務(wù);并且在任意時(shí)間點(diǎn)盼铁,不會(huì)有多個(gè)線程是活動(dòng)的應(yīng)用場(chǎng)景

        • SingleThreadExecutor 的 corePoolSize 和 maximumPoolSize 都被設(shè)置為1蛾默,其余參數(shù)都與FixedThreadPool 相同,也是使用了無(wú)界隊(duì)列LinkedBlockingQueue作為線程池的工作隊(duì)列捉貌。帶來(lái)的影響跟 FixedThreadPool 相同

          ?

      • CachedThreadPool:大小無(wú)界的線程池支鸡,Executors 的 newCachedThreadPool 方法提供了兩個(gè)API

        • public static ExecutorService newCachedThreadPool() {
            return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                          60L, TimeUnit.SECONDS,
                                          new SynchronousQueue<Runnable>());
          }
          
          public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
            return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                          60L, TimeUnit.SECONDS,
                                          new SynchronousQueue<Runnable>(),
                                          threadFactory);
          }
          
        • CachedThreadPool 是大小無(wú)界的線程池,適用于執(zhí)行很多短期的異步任務(wù)的小程序趁窃,或者是負(fù)載較輕的服務(wù)器

        • CachedThreadPool 的 corePoolSize 為0牧挣,但是 maximumPoolSize 被設(shè)置為Integer.MAX_VALUE ,所以可以說(shuō)是 無(wú)界的醒陆,這里把 keepAliveTime 設(shè)置為 60L 意味著線程池中的空閑線程最長(zhǎng)等待時(shí)間為60秒瀑构,超過(guò)將被終止

        • CachedThreadPool 使用的是沒(méi)有容量的 SynchronousQueue 隊(duì)列作為線程池的工作隊(duì)列,但maximumPoolSize 是無(wú)界的刨摩。這意味著寺晌,如果主線程提交任務(wù)的速度高于 maximumPoolSize 中的線程處理任務(wù)的速度時(shí),CachedThreadPool將會(huì)不斷的創(chuàng)建新的線程澡刹,極端的情況下會(huì)因?yàn)閯?chuàng)建過(guò)多的線程而耗盡CPU 和 內(nèi)存的資源

          ?

    • (2)ScheduledThreadPoolExecutor (定時(shí)任務(wù)):

      • ScheduledThreadPoolExecutor任務(wù)傳遞圖
      • ScheduledThreadPoolExecutor 通常使用 Executors 來(lái)創(chuàng)建呻征。 可以創(chuàng)建兩種類型的 ScheduledThreadPoolExecutor, 如下: 的 newScheduledThreadPool() 方法

        • ScheduledThreadPoolExecutor 包含若干線程的 ScheduledThreadPoolExecutor
        • SingleThreadScheduledExecutor 只包含一個(gè)線程的 ScheduledThreadPoolExecutor
      • 創(chuàng)建固定個(gè)數(shù)線程的 ScheduledThreadPoolExecutor API:

        • public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize){
            return new ScheduledThreadPoolExecutor(corePoolSize);
          }
          
          public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize,                         ThreadFactory threadFactory) {
            return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
          }
          
          // --------------------
          
          public ScheduledThreadPoolExecutor(int corePoolSize) {
            super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
                  new DelayedWorkQueue());
          }
          
          public ScheduledThreadPoolExecutor(int corePoolSize,
                                                 ThreadFactory threadFactory) {
            super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
                  new DelayedWorkQueue(), threadFactory);
          }
          
        • ScheduledThreadPoolExecutor 適用于需要多個(gè)后臺(tái)線程執(zhí)行周期任務(wù)罢浇,同時(shí)為了滿足資源管理的需求而需要限制后臺(tái)線程的數(shù)量的應(yīng)用場(chǎng)景陆赋。內(nèi)部實(shí)際上是用延遲隊(duì)列 DelayedWorkQueue 來(lái)實(shí)現(xiàn)

      • 創(chuàng)建單個(gè)線程的 SingleThreadScheduledExecutor 的 API:

        • public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
            return new DelegatedScheduledExecutorService
              (new ScheduledThreadPoolExecutor(1));
          }
          
          public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
            return new DelegatedScheduledExecutorService
              (new ScheduledThreadPoolExecutor(1, threadFactory));
          }
          
        • 內(nèi)部實(shí)際上還是用 new ScheduledThreadPoolExecutor 的發(fā)那個(gè)是實(shí)現(xiàn)沐祷,但是包裝了一層委托 DelegatedScheduledExecutorService

        • 適用于需要單個(gè)后臺(tái)線程執(zhí)行周期任務(wù),同時(shí)需要保證順序地執(zhí)行各個(gè)任務(wù)的應(yīng)用場(chǎng)景

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末攒岛,一起剝皮案震驚了整個(gè)濱河市赖临,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌灾锯,老刑警劉巖兢榨,帶你破解...
    沈念sama閱讀 216,496評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異顺饮,居然都是意外死亡吵聪,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門领突,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)暖璧,“玉大人案怯,你說(shuō)我怎么就攤上這事君旦。” “怎么了嘲碱?”我有些...
    開封第一講書人閱讀 162,632評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵金砍,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我麦锯,道長(zhǎng)恕稠,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,180評(píng)論 1 292
  • 正文 為了忘掉前任扶欣,我火速辦了婚禮鹅巍,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘料祠。我一直安慰自己骆捧,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評(píng)論 6 388
  • 文/花漫 我一把揭開白布髓绽。 她就那樣靜靜地躺著敛苇,像睡著了一般。 火紅的嫁衣襯著肌膚如雪顺呕。 梳的紋絲不亂的頭發(fā)上枫攀,一...
    開封第一講書人閱讀 51,165評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音株茶,去河邊找鬼来涨。 笑死,一個(gè)胖子當(dāng)著我的面吹牛启盛,可吹牛的內(nèi)容都是我干的扫夜。 我是一名探鬼主播楞泼,決...
    沈念sama閱讀 40,052評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼笤闯!你這毒婦竟也來(lái)了堕阔?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,910評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤颗味,失蹤者是張志新(化名)和其女友劉穎超陆,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體浦马,經(jīng)...
    沈念sama閱讀 45,324評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡时呀,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評(píng)論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了晶默。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片谨娜。...
    茶點(diǎn)故事閱讀 39,711評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖磺陡,靈堂內(nèi)的尸體忽然破棺而出趴梢,到底是詐尸還是另有隱情,我是刑警寧澤币他,帶...
    沈念sama閱讀 35,424評(píng)論 5 343
  • 正文 年R本政府宣布坞靶,位于F島的核電站,受9級(jí)特大地震影響蝴悉,放射性物質(zhì)發(fā)生泄漏彰阴。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評(píng)論 3 326
  • 文/蒙蒙 一拍冠、第九天 我趴在偏房一處隱蔽的房頂上張望尿这。 院中可真熱鬧,春花似錦庆杜、人聲如沸射众。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)责球。三九已至,卻和暖如春拓劝,著一層夾襖步出監(jiān)牢的瞬間雏逾,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工郑临, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留栖博,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,722評(píng)論 2 368
  • 正文 我出身青樓厢洞,卻偏偏與公主長(zhǎng)得像仇让,于是被迫代替她去往敵國(guó)和親典奉。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容