自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

面試必問:線程池是如何執(zhí)行的?它的拒絕策略有哪些?

開發(fā) 前端
線程池的執(zhí)行流程有 3 個(gè)重要的判斷點(diǎn)(判斷順序依次往后):判斷當(dāng)前線程數(shù)和核心線程數(shù)、判斷當(dāng)前任務(wù)隊(duì)列是否已滿、判斷當(dāng)前線程數(shù)是否已達(dá)到最大線程數(shù)。

聊到線程池就一定會(huì)聊到線程池的執(zhí)行流程,也就是當(dāng)有一個(gè)任務(wù)進(jìn)入線程池之后,線程池是如何執(zhí)行的?我們今天就來聊聊這個(gè)話題。線程池是如何執(zhí)行的?線程池的拒絕策略有哪些?

線程池執(zhí)行流程

想要真正的了解線程池的執(zhí)行流程,就得先從線程池的執(zhí)行方法 execute() 說起,execute() 實(shí)現(xiàn)源碼如下:

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    int c = ctl.get();
    // 當(dāng)前工作的線程數(shù)小于核心線程數(shù)
    if (workerCountOf(c) < corePoolSize) {
        // 創(chuàng)建新的線程執(zhí)行此任務(wù)
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    // 檢查線程池是否處于運(yùn)行狀態(tài),如果是則把任務(wù)添加到隊(duì)列
    if (isRunning(c) && workQueue.offer(command)) {
        int recheck = ctl.get();
        // 再次檢線程池是否處于運(yùn)行狀態(tài),防止在第一次校驗(yàn)通過后線程池關(guān)閉
        // 如果是非運(yùn)行狀態(tài),則將剛加入隊(duì)列的任務(wù)移除
        if (! isRunning(recheck) && remove(command))
            reject(command);
        // 如果線程池的線程數(shù)為 0 時(shí)(當(dāng) corePoolSize 設(shè)置為 0 時(shí)會(huì)發(fā)生)
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false); // 新建線程執(zhí)行任務(wù)
    }
    // 核心線程都在忙且隊(duì)列都已爆滿,嘗試新啟動(dòng)一個(gè)線程執(zhí)行失敗
    else if (!addWorker(command, false)) 
        // 執(zhí)行拒絕策略
        reject(command);
}

從上述源碼我們可以看出,當(dāng)任務(wù)來了之后,線程池的執(zhí)行流程是:先判斷當(dāng)前線程數(shù)是否大于核心線程數(shù)?如果結(jié)果為 false,則新建線程并執(zhí)行任務(wù);如果結(jié)果為 true,則判斷任務(wù)隊(duì)列是否已滿?如果結(jié)果為 false,則把任務(wù)添加到任務(wù)隊(duì)列中等待線程執(zhí)行,否則則判斷當(dāng)前線程數(shù)量是否超過最大線程數(shù)?如果結(jié)果為 false,則新建線程執(zhí)行此任務(wù),否則將執(zhí)行線程池的拒絕策略,如下圖所示:

線程池拒絕策略

當(dāng)任務(wù)過多且線程池的任務(wù)隊(duì)列已滿時(shí),此時(shí)就會(huì)執(zhí)行線程池的拒絕策略,線程池的拒絕策略默認(rèn)有以下 4 種:

  1. AbortPolicy:中止策略,線程池會(huì)拋出異常并中止執(zhí)行此任務(wù)。
  2. CallerRunsPolicy:把任務(wù)交給添加此任務(wù)的(main)線程來執(zhí)行。
  3. DiscardPolicy:忽略此任務(wù),忽略最新的一個(gè)任務(wù)。
  4. DiscardOldestPolicy:忽略最早的任務(wù),最先加入隊(duì)列的任務(wù)。

默認(rèn)的拒絕策略為 AbortPolicy 中止策略。

DiscardPolicy拒絕策略

接下來我們以 DiscardPolicy 忽略此任務(wù),忽略最新的一個(gè)任務(wù)為例,演示一下拒絕策略的具體使用,實(shí)現(xiàn)代碼如下:

public static void main(String[] args) {
    // 任務(wù)的具體方法
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            System.out.println("當(dāng)前任務(wù)被執(zhí)行,執(zhí)行時(shí)間:" + new Date() +
                               " 執(zhí)行線程:" + Thread.currentThread().getName());
            try {
                // 等待 1s
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    // 創(chuàng)建線程,線程的任務(wù)隊(duì)列的長度為 1
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 1,
                                                           100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1),
                                                           new ThreadPoolExecutor.DiscardPolicy());
    // 添加并執(zhí)行 4 個(gè)任務(wù)
    threadPool.execute(runnable);
    threadPool.execute(runnable);
    threadPool.execute(runnable);
    threadPool.execute(runnable);
    // 線程池執(zhí)行完任務(wù),關(guān)閉線程池
    threadPool.shutdown();
}

以上程序的執(zhí)行結(jié)果如下:

從上述執(zhí)行結(jié)果可以看出,給線程池添加了 4 個(gè)任務(wù),而線程池只執(zhí)行了 2 個(gè)任務(wù)就結(jié)束了,其他兩個(gè)任務(wù)執(zhí)行了拒絕策略 DiscardPolicy 被忽略了,這就是拒絕策略的作用。

AbortPolicy拒絕策略

為了和 DiscardPolicy 拒絕策略對(duì)比,我們來演示一下 JDK 默認(rèn)的拒絕策略 AbortPolicy 中止策略,線程池會(huì)拋出異常并中止執(zhí)行此任務(wù),示例代碼如下:

public static void main(String[] args) {
    // 任務(wù)的具體方法
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            System.out.println("當(dāng)前任務(wù)被執(zhí)行,執(zhí)行時(shí)間:" + new Date() +
                               " 執(zhí)行線程:" + Thread.currentThread().getName());
            try {
                // 等待 1s
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    // 創(chuàng)建線程,線程的任務(wù)隊(duì)列的長度為 1
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 1,
                                                           100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1),
                                                           new ThreadPoolExecutor.AbortPolicy()); // 顯式指定拒絕策略,也可以忽略此設(shè)置,它為默認(rèn)拒絕策略
    // 添加并執(zhí)行 4 個(gè)任務(wù)
    threadPool.execute(runnable);
    threadPool.execute(runnable);
    threadPool.execute(runnable);
    threadPool.execute(runnable);
    // 線程池執(zhí)行完任務(wù),關(guān)閉線程池
    threadPool.shutdown();
}

以上程序的執(zhí)行結(jié)果如下:

從結(jié)果可以看出,給線程池添加了 4 個(gè)任務(wù),線程池正常執(zhí)行了 2 個(gè)任務(wù),其他兩個(gè)任務(wù)執(zhí)行了中止策略,并拋出了拒絕執(zhí)行的異常 RejectedExecutionException。

自定義拒絕策略

當(dāng)然除了 JDK 提供的四種拒絕策略之外,我們還可以實(shí)現(xiàn)通過 new RejectedExecutionHandler,并重寫 rejectedExecution 方法來實(shí)現(xiàn)自定義拒絕策略,實(shí)現(xiàn)代碼如下:

public static void main(String[] args) {
    // 任務(wù)的具體方法
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            System.out.println("當(dāng)前任務(wù)被執(zhí)行,執(zhí)行時(shí)間:" + new Date() +
                               " 執(zhí)行線程:" + Thread.currentThread().getName());
            try {
                // 等待 1s
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    // 創(chuàng)建線程,線程的任務(wù)隊(duì)列的長度為 1
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 1,
                                                           100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1),
                                                           new RejectedExecutionHandler() {
                                                               @Override
                                                               public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                                                                   // 執(zhí)行自定義拒絕策略的相關(guān)操作
                                                                   System.out.println("我是自定義拒絕策略~");
                                                               }
                                                           });
    // 添加并執(zhí)行 4 個(gè)任務(wù)
    threadPool.execute(runnable);
    threadPool.execute(runnable);
    threadPool.execute(runnable);
    threadPool.execute(runnable);
}

以上程序的執(zhí)行結(jié)果如下:

小結(jié)

線程池的執(zhí)行流程有 3 個(gè)重要的判斷點(diǎn)(判斷順序依次往后):判斷當(dāng)前線程數(shù)和核心線程數(shù)、判斷當(dāng)前任務(wù)隊(duì)列是否已滿、判斷當(dāng)前線程數(shù)是否已達(dá)到最大線程數(shù)。如果經(jīng)過以上 3 個(gè)判斷,得到的結(jié)果都會(huì) true,則會(huì)執(zhí)行線程池的拒絕策略。JDK 提供了 4 種拒絕策略,我們還可以通過 new RejectedExecutionHandler 并重寫 rejectedExecution 方法來實(shí)現(xiàn)自定義拒絕策略。

責(zé)任編輯:姜華 來源: Java面試真題解析
相關(guān)推薦

2022-03-14 07:32:06

線程池拒絕策略自定義

2020-02-18 14:25:51

Java線程池拒絕策略

2024-11-11 17:27:45

2024-08-19 09:13:02

2024-06-04 07:38:10

2025-02-11 08:31:37

Java關(guān)鍵字安全

2020-11-25 11:33:47

Java線程技術(shù)

2022-03-23 08:51:21

線程池Java面試題

2021-12-09 12:22:28

MyBatis流程面試

2011-11-14 09:08:06

云計(jì)算數(shù)據(jù)存儲(chǔ)

2023-09-01 15:22:31

負(fù)載均衡服務(wù)器端客戶端

2021-02-05 12:34:33

線程池系統(tǒng)

2024-01-05 14:20:55

MySQL索引優(yōu)化器

2023-02-06 07:01:51

2021-12-13 11:12:41

Spring事務(wù)失效

2018-10-24 14:30:30

緩存服務(wù)更新

2023-02-03 07:24:49

雙親委派模型

2020-07-08 12:05:55

Java線程池策略

2024-10-09 15:58:02

2023-02-15 07:03:41

跨域問題面試安全
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)