標籤: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線程池停止空閑線程是否有規則呢?