java中創(chuàng)建線程池的方式

創(chuàng)建線程池的方式:

使用Java提供的用于管理線程池的接口ExecutorService 創(chuàng)建線程池,共有四種方式:

Executors.newCachedThreadPool();
Executors.newFixedThreadPool(10);
Executors.newScheduledThreadPool(10);
Executors.newSingleThreadExecutor();
// 獲取當前主機的處理器cpu的可用個數,可根據該參數來修改線程池的大小
System.out.println("處理器的可用個數:" + Runtime.getRuntime().availableProcessors());

1窄做、 newCachedThreadPool

創(chuàng)建一個可根據需要創(chuàng)建新線程的線程池队询,在以前創(chuàng)建的線程可用時重用它們。該線程池可緩存泼差,無限大贵少。

public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < 10; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getId());
            }
        });
    }
}

源碼:

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}

// 上面返回的對象指向下面的 ThreadPoolExecutor(...) 構造方法
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}

參數的意義:

  • corePoolSize :核心線程池的數量
  • maximumPoolSize :線程池的最大數量, Integer.MAX_VALUE 可以看作是無限的
  • keepAliveTime : 線程保持活躍狀態(tài)的時間
  • unit : 時間單位
  • workQueue : 工作隊列堆缘,SynchronousQueue 是一個不存儲元素的隊列滔灶,可以理解為隊列已滿

根據上面的源碼可知:
當調用該方法創(chuàng)建線程池時,workQueue 為0吼肥,不創(chuàng)建核心線程宽气,且隊列已滿,因此會創(chuàng)建非核心線程執(zhí)行任務潜沦。對于非核心線程空閑60s就會被回收萄涯,而線程池的數量幾乎是無限的,當資源有限時易引起OOM異常唆鸡。

2涝影、newFixedThreadPool

創(chuàng)建一個可重用固定線程集合的線程池,以共享的無界隊列方式運行線程争占。
定長的線程池燃逻,可控制線程最大并發(fā)數,超出的線程會在隊列中等待臂痕。

public static void main(String[] args) {
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getId());
            }
        });
    }
}

源碼:

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
}


// 上面返回的對象指向下面的 ThreadPoolExecutor(...) 構造方法
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}

說明

參數與SingleThreadExecutor 一致伯襟,區(qū)別是核心線程數是由用戶傳入的。

3握童、newSingleThreadExecutor

創(chuàng)建一個使用單個worker線程的線程池姆怪,以無界隊列的方式運行。
該線程池只存在一個線程澡绩,會按照順序執(zhí)行稽揭,不同與單線程。

public static void main(String[] args) {
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    for (int i = 0; i < 10; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getId());
            }
        });
    }
}

源碼:

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
}

// 上面返回的對象指向下面的 ThreadPoolExecutor(...) 構造方法
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}

說明

返回的核心線程池數量為1肥卡,最大線程池數量為1溪掀,即只能創(chuàng)建一個非核心線程。

4步鉴、newScheduledThreadPool

創(chuàng)建一個線程池揪胃,可安排在給定延遲后運行命令或定期執(zhí)行璃哟。
定長線的程池,支持定時及周期性任務執(zhí)行喊递。

public static void main(String[] args) {
    ExecutorService executorService = Executors.newScheduledThreadPool(10);
    for (int i = 0; i < 10; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getId());
            }
        });
    }
}

源碼:

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

// 上面返回的對象指向下面的構造方法
public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue());
}

// 查看ScheduledThreadPoolExecutor 的類沮稚,發(fā)現其繼承了ThreadPoolExecutor,并實現了ScheduledExecutorService接口
public class ScheduledThreadPoolExecutor extends ThreadPoolExecutor implements ScheduledExecutorService {...}


// 繼續(xù)追蹤父類的構造方法
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}

// this(...)方法對應的如下:
public ThreadPoolExecutor(int corePoolSize,         // 核心線程池數量
                          int maximumPoolSize,      // 最大線程數
                          long keepAliveTime,       // 保持線程存活時間
                          TimeUnit unit,            // 時間單位
                          BlockingQueue<Runnable> workQueue,     // 保存任務的阻塞隊列
                          ThreadFactory threadFactory,         // 創(chuàng)建線程的工廠
                          RejectedExecutionHandler handler) {     // 拒接策略
    if (corePoolSize < 0 ||
        maximumPoolSize <= 0 ||
        maximumPoolSize < corePoolSize ||
        keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

其他方式

// 通過ScheduledExecutorService(繼承了ExecutorService)接口册舞,調用schedule方法蕴掏,通過該方法中的參數設置可以設置執(zhí)行時間。
// 該方法的第二個调鲸、第三個參數結合設置從當前開始推遲設置的時間來執(zhí)行
public static void main(String[] args) {
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
    for (int i = 0; i < 10; i++) {
        scheduledThreadPool.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getId());
            }
        }, 3, TimeUnit.SECONDS);
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末盛杰,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子藐石,更是在濱河造成了極大的恐慌即供,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件于微,死亡現場離奇詭異逗嫡,居然都是意外死亡,警方通過查閱死者的電腦和手機株依,發(fā)現死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門驱证,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人恋腕,你說我怎么就攤上這事抹锄。” “怎么了荠藤?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵伙单,是天一觀的道長。 經常有香客問我哈肖,道長吻育,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任淤井,我火速辦了婚禮布疼,結果婚禮上,老公的妹妹穿的比我還像新娘庄吼。我一直安慰自己缎除,他們只是感情好,可當我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布总寻。 她就那樣靜靜地躺著,像睡著了一般梢为。 火紅的嫁衣襯著肌膚如雪渐行。 梳的紋絲不亂的頭發(fā)上轰坊,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天,我揣著相機與錄音祟印,去河邊找鬼肴沫。 笑死,一個胖子當著我的面吹牛蕴忆,可吹牛的內容都是我干的颤芬。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼套鹅,長吁一口氣:“原來是場噩夢啊……” “哼站蝠!你這毒婦竟也來了?” 一聲冷哼從身側響起卓鹿,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤菱魔,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后吟孙,有當地人在樹林里發(fā)現了一具尸體澜倦,經...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年杰妓,在試婚紗的時候發(fā)現自己被綠了藻治。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡巷挥,死狀恐怖栋艳,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情句各,我是刑警寧澤吸占,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站凿宾,受9級特大地震影響矾屯,放射性物質發(fā)生泄漏。R本人自食惡果不足惜初厚,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一件蚕、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧产禾,春花似錦排作、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至楞件,卻和暖如春衫生,著一層夾襖步出監(jiān)牢的瞬間裳瘪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工罪针, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留彭羹,地道東北人。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓泪酱,卻偏偏與公主長得像派殷,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子墓阀,可洞房花燭夜當晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內容