ExecutorService線程池的理解和使用

一. 線程池

我們之前使用線程的時候都是使用new Thread來進行線程的創建,但是這樣會有一些問題。如:

  • a. 每次new Thread新建對象性能差。
  • b. 線程缺乏統一管理,可能無限制新建線程,相互之間競爭,及可能佔用過多系統資源導致死機或oom。
  • c. 缺乏更多功能,如定時執行、定期執行、線程中斷。

相比new Thread,Java提供的四種線程池的好處在於:

  • a. 重用存在的線程,減少對象創建、消亡的開銷,性能佳。
  • b. 可有效控制最大併發線程數,提高系統資源的使用率,同時避免過多資源競爭,避免堵塞。
  • c. 提供定時執行、定期執行、單線程、併發數控制等功能。

二. 線程池的體系結構

java.util.concurrent.Executor 負責線程的使用和調度的根接口
        |--ExecutorService 子接口: 線程池的主要接口
                |--ThreadPoolExecutor 線程池的實現類
                |--ScheduledExceutorService 子接口: 負責線程的調度
                    |--ScheduledThreadPoolExecutor : 繼承ThreadPoolExecutor,實現了ScheduledExecutorService

三. 工具類:Executors

ExecutorService newFixedThreadPool() : 創建固定大小的線程池
ExecutorService newCachedThreadPool() : 緩存線程池,線程池的數量不固定,可以根據需求自動的更改數量。
ExecutorService newSingleThreadExecutor() : 創建單個線程池。 線程池中只有一個線程
ScheduledExecutorService newScheduledThreadPool() : 創建固定大小的線程,可以延遲或定時的執行任務

四. 舉例

1. newCachedThreadPool

創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閒線程,若無可回收,則新建線程。

/**
 * 創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閒線程,若無可回收,則新建線程。
 * 線程池爲無限大,當執行第二個任務時第一個任務已經完成,會複用執行第一個任務的線程,而不用每次新建線程。
 *
 * @throws InterruptedException
 */
public static void cachedThreadPool() throws InterruptedException {
    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    for(int i = 0; i < 10; i++) {
        final int index = i;

        // 加上這一行代碼,讓前面的線程執行完成,可以看出,一直用的都是同一個線程,沒有新建
        TimeUnit.SECONDS.sleep(1);
        cachedThreadPool.execute(() - > {
            System.out.println(Thread.currentThread() + "====" + index);
        });
    }
}

加上TimeUnit.SECONDS.sleep(1);執行結果:
一直複用的是同一個線程

Thread[pool-1-thread-1,5,main]====0
Thread[pool-1-thread-1,5,main]====1
Thread[pool-1-thread-1,5,main]====2
Thread[pool-1-thread-1,5,main]====3
Thread[pool-1-thread-1,5,main]====4
Thread[pool-1-thread-1,5,main]====5
Thread[pool-1-thread-1,5,main]====6
Thread[pool-1-thread-1,5,main]====7
Thread[pool-1-thread-1,5,main]====8
Thread[pool-1-thread-1,5,main]====9

去掉TimeUnit.SECONDS.sleep(1);執行結果:
創建了10個不同的線程

 Thread[pool-1-thread-1,5,main]====0
Thread[pool-1-thread-2,5,main]====1
Thread[pool-1-thread-3,5,main]====2
Thread[pool-1-thread-4,5,main]====3
Thread[pool-1-thread-5,5,main]====4
Thread[pool-1-thread-6,5,main]====5
Thread[pool-1-thread-7,5,main]====6
Thread[pool-1-thread-9,5,main]====8
Thread[pool-1-thread-8,5,main]====7
Thread[pool-1-thread-10,5,main]====9

2. newFixedThreadPool

創建一個定長線程池,可控制線程最大併發數,超出的線程會在隊列中等待。

/**
 * 創建一個定長線程池,可控制線程最大併發數,超出的線程會在隊列中等待。
 * 本例中,因爲線程池大小爲3,每個任務輸出index後sleep 2秒,所以每兩秒打印3個數字。
 */
public static void fixedThreadPool() {
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
    for(int i = 0; i < 10; i++) {
        final int index = i;
        fixedThreadPool.execute(() - > {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread() + "====" + index);
        });
    }
}

執行結果:
因爲線程池大小爲3,只會創建3個線程,每個任務輸出index後sleep 2秒,所以每兩秒打印3個數字。

Thread[pool-1-thread-1,5,main]====0
Thread[pool-1-thread-3,5,main]====2
Thread[pool-1-thread-2,5,main]====1
Thread[pool-1-thread-1,5,main]====3
Thread[pool-1-thread-3,5,main]====4
Thread[pool-1-thread-2,5,main]====5
Thread[pool-1-thread-1,5,main]====6
Thread[pool-1-thread-3,5,main]====7
Thread[pool-1-thread-2,5,main]====8
Thread[pool-1-thread-1,5,main]====9

3. newScheduledThreadPool

創建一個定長線程池,支持定時及週期性任務執行。

/**
 * 創建一個定長線程池,延遲1秒,每隔1秒週期性任務執行
 */
public static void scheduledThreadPool() {
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
    scheduledThreadPool.scheduleAtFixedRate(() - > {
        System.out.println("scheduledThreadPool執行中...");
    }, 1, 1, TimeUnit.SECONDS);
}

執行結果:

scheduledThreadPool執行中...
scheduledThreadPool執行中...
......
scheduledThreadPool執行中...
scheduledThreadPool執行中...
......

4. newSingleThreadExecutor

創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行。

/**
 * 創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行
 */
public static void singleThreadExecutor() {
    ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    for(int i = 0; i < 10; i++) {
        final int index = i;
        singleThreadExecutor.execute(() - > {
            System.out.println(Thread.currentThread() + "====" + index);
        });
    }
}

執行結果:
只會創建一個線程

Thread[pool-1-thread-1,5,main]====0
Thread[pool-1-thread-1,5,main]====1
Thread[pool-1-thread-1,5,main]====2
Thread[pool-1-thread-1,5,main]====3
Thread[pool-1-thread-1,5,main]====4
Thread[pool-1-thread-1,5,main]====5
Thread[pool-1-thread-1,5,main]====6
Thread[pool-1-thread-1,5,main]====7
Thread[pool-1-thread-1,5,main]====8
Thread[pool-1-thread-1,5,main]====9
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章