功能線程池

Executors封裝好 4 種常見的功能線程池讳苦,如下:

  • 定長線程池(FixedThreadPool)
  • 定時線程池(ScheduledThreadPool )
  • 可緩存線程池(CachedThreadPool)
  • 單線程化線程池(SingleThreadExecutor)

定長線程池(FixedThreadPool)

創(chuàng)建方法:

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);
}

特點

只有核心線程气忠,線程數(shù)量固定着饥,執(zhí)行完立即回收,任務隊列為鏈表結構的有界隊列哺徊。

應用場景

控制線程最大并發(fā)數(shù)缺虐。

使用示例

// 1. 創(chuàng)建定長線程池對象 & 設置線程池線程數(shù)量固定為3
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
// 2. 創(chuàng)建好Runnable類線程對象 & 需執(zhí)行的任務
Runnable task =new Runnable(){
  public void run() {
     System.out.println("執(zhí)行任務啦");
  }
};
// 3. 向線程池提交任務
fixedThreadPool.execute(task);

定時線程池(ScheduledThreadPool )

創(chuàng)建方法:

private static final long DEFAULT_KEEPALIVE_MILLIS = 10L;
 
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE,
          DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
          new DelayedWorkQueue());
}
 
public static ScheduledExecutorService newScheduledThreadPool(
        int corePoolSize, ThreadFactory threadFactory) {
    return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
public ScheduledThreadPoolExecutor(int corePoolSize,
                                   ThreadFactory threadFactory) {
    super(corePoolSize, Integer.MAX_VALUE,
          DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
          new DelayedWorkQueue(), threadFactory);
}

特點

核心線程數(shù)量固定,非核心線程數(shù)量無限齐帚,執(zhí)行完閑置 10ms 后回收,任務隊列為延時阻塞隊列彼哼。

應用場景

執(zhí)行定時或周期性的任務对妄。

使用示例

// 1. 創(chuàng)建 定時線程池對象 & 設置線程池線程數(shù)量固定為5
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
// 2. 創(chuàng)建好Runnable類線程對象 & 需執(zhí)行的任務
Runnable task =new Runnable(){
  public void run() {
     System.out.println("執(zhí)行任務啦");
  }
};
// 3. 向線程池提交任務
scheduledThreadPool.schedule(task, 1, TimeUnit.SECONDS); // 延遲1s后執(zhí)行任務
scheduledThreadPool.scheduleAtFixedRate(task,10,1000,TimeUnit.MILLISECONDS);// 延遲10ms后、每隔1000ms執(zhí)行任務

可緩存線程池(CachedThreadPool)

創(chuàng)建方法:

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);
}

特點

無核心線程敢朱,非核心線程數(shù)量無限饥伊,執(zhí)行完閑置 60s 后回收,任務隊列為不存儲元素的阻塞隊列蔫饰。

應用場景

執(zhí)行大量、耗時少的任務愉豺。

使用示例

// 1. 創(chuàng)建可緩存線程池對象
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
// 2. 創(chuàng)建好Runnable類線程對象 & 需執(zhí)行的任務
Runnable task =new Runnable(){
  public void run() {
     System.out.println("執(zhí)行任務啦");
  }
};
// 3. 向線程池提交任務
cachedThreadPool.execute(task);

單線程化線程池(SingleThreadExecutor)

創(chuàng)建方法:

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));
}

特點

只有 1 個核心線程篓吁,無非核心線程,執(zhí)行完立即回收蚪拦,任務隊列為鏈表結構的有界隊列杖剪。

應用場景

不適合并發(fā)但可能引起 IO 阻塞性及影響 UI 線程響應的操作,如數(shù)據(jù)庫操作驰贷、文件操作等盛嘿。

使用示例

// 1. 創(chuàng)建單線程化線程池
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
// 2. 創(chuàng)建好Runnable類線程對象 & 需執(zhí)行的任務
Runnable task =new Runnable(){
  public void run() {
     System.out.println("執(zhí)行任務啦");
  }
};
// 3. 向線程池提交任務
singleThreadExecutor.execute(task);

對比

線程池對比
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市括袒,隨后出現(xiàn)的幾起案子次兆,更是在濱河造成了極大的恐慌,老刑警劉巖锹锰,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件芥炭,死亡現(xiàn)場離奇詭異漓库,居然都是意外死亡,警方通過查閱死者的電腦和手機园蝠,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門渺蒿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人彪薛,你說我怎么就攤上這事茂装。” “怎么了善延?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵少态,是天一觀的道長。 經(jīng)常有香客問我挚冤,道長况增,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任训挡,我火速辦了婚禮澳骤,結果婚禮上,老公的妹妹穿的比我還像新娘澜薄。我一直安慰自己为肮,他們只是感情好,可當我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布肤京。 她就那樣靜靜地躺著颊艳,像睡著了一般。 火紅的嫁衣襯著肌膚如雪忘分。 梳的紋絲不亂的頭發(fā)上棋枕,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天,我揣著相機與錄音妒峦,去河邊找鬼重斑。 笑死,一個胖子當著我的面吹牛肯骇,可吹牛的內(nèi)容都是我干的窥浪。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼笛丙,長吁一口氣:“原來是場噩夢啊……” “哼漾脂!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起胚鸯,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤骨稿,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年蒲牧,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片趟脂。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖例衍,靈堂內(nèi)的尸體忽然破棺而出昔期,到底是詐尸還是另有隱情,我是刑警寧澤佛玄,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布硼一,位于F島的核電站,受9級特大地震影響梦抢,放射性物質(zhì)發(fā)生泄漏般贼。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一奥吩、第九天 我趴在偏房一處隱蔽的房頂上張望哼蛆。 院中可真熱鬧,春花似錦霞赫、人聲如沸腮介。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽叠洗。三九已至,卻和暖如春旅东,著一層夾襖步出監(jiān)牢的瞬間灭抑,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工抵代, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留腾节,地道東北人。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓主守,卻偏偏與公主長得像,于是被迫代替她去往敵國和親榄融。 傳聞我的和親對象是個殘疾皇子参淫,可洞房花燭夜當晚...
    茶點故事閱讀 44,713評論 2 354

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