Java線程池停止空閑線程是否有規則呢?

來源:互聯網
上載者:User

標籤:lex   執行   down   pool   print   結果   class   try   trace   

Java線程池中線程的數量超過核心線程的數量,且所有線程空閑,空閑時間超過keepAliveTime,會停止超過核心線程數量的線程,那麼會保留哪些線程呢?是不是有規則呢?

測試代碼:
       ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5));        int taskNum = 13;        for (int i = 0; i < taskNum; i++) {            final int finalI = i;            if (i == 10) {                System.out.println("執行過10個任務,開始空閑");                try {                    TimeUnit.SECONDS.sleep(10);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            System.out.println("提交任務:" + (i + 1));            executor.submit(new Runnable() {                public void run() {                    Integer taskNum = finalI + 1;                    System.out.println("task: " + taskNum + ", " + Thread.currentThread().getName() + ", " + System.currentTimeMillis());                }            });        }
運行結果
提交任務:1提交任務:2提交任務:3提交任務:4提交任務:5提交任務:6提交任務:7提交任務:8提交任務:9提交任務:10執行過10個任務,開始空閑task: 2, pool-1-thread-2, 1522134893596task: 1, pool-1-thread-1, 1522134893596task: 3, pool-1-thread-3, 1522134893596task: 9, pool-1-thread-4, 1522134893596task: 4, pool-1-thread-2, 1522134893596task: 6, pool-1-thread-4, 1522134893596task: 5, pool-1-thread-3, 1522134893596task: 8, pool-1-thread-1, 1522134893596task: 7, pool-1-thread-2, 1522134893596task: 10, pool-1-thread-5, 1522134893596提交任務:11提交任務:12提交任務:13task: 11, pool-1-thread-6, 1522134903606task: 13, pool-1-thread-8, 1522134903606task: 12, pool-1-thread-7, 1522134903606

根據多次實驗,發現每次保留作為核心線程的線程並沒規律或規則。因此,線程池中線程數量達到最大允許的線程數量,然後所有線程都同時進入空閑狀態且空閑時間超過keepAliveTime,停止多餘的線程並保留核心數量的線程是沒有規律或規則。

Java線程池停止空閑線程是否有規則呢?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.