1. 程式人生 > >Java線程池停止空閑線程是否有規則呢?

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

read ali 是否 線程 stack fin down oid 規律

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, 1522134893596
task: 1, pool-1-thread-1, 1522134893596
task: 3, pool-1-thread-3, 1522134893596
task: 9, pool-1-thread-4, 1522134893596
task: 4, pool-1-thread-2, 1522134893596
task: 6, pool-1-thread-4, 1522134893596
task: 5, pool-1-thread-3, 1522134893596
task: 8, pool-1-thread-1, 1522134893596
task: 7, pool-1-thread-2, 1522134893596
task: 10, pool-1-thread-5, 1522134893596
提交任務:11
提交任務:12
提交任務:13
task: 11, pool-1-thread-6, 1522134903606
task: 13, pool-1-thread-8, 1522134903606
task: 12, pool-1-thread-7, 1522134903606

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

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