
初次了解自定义线程池 ThreadPoolExecutor 的小伙伴,可以先看这篇文章:有界、无界队列对ThreadPoolExcutor执行的影响
allowCoreThreadTimeOut :方法作用:设置是否回收在保活时间后依然没没有任务执行核心线程。
public class PoolThreadRecycling {private static final int CORE_POOL_SIZE = 5;private static final int MAX_POOL_SIZE = 10;private static final int QUEUE_CAPACITY = 1;private static final Long KEEP_ALIVE_TIME = 1L;private static ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_POOL_SIZE,MAX_POOL_SIZE,KEEP_ALIVE_TIME,TimeUnit.SECONDS,new ArrayBlockingQueue<>(QUEUE_CAPACITY),new ThreadPoolExecutor.CallerRunsPolicy());static {//如果设置为true,当任务执行完后,所有的线程在指定的空闲时间后,poolSize会为0//如果不设置,或者设置为false,那么,poolSize会保留为核心线程的数量executor.allowCoreThreadTimeOut(true);}public static void main(String[] args) throws InterruptedException {CountDownLatch countDownLatch = new CountDownLatch(10);for (int i = 1; i <= 10; i++) {executor.submit(() -> {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} finally {countDownLatch.countDown();}});}System.out.println("poolSize:" + executor.getPoolSize());System.out.println("core:" + executor.getCorePoolSize());System.out.println("活跃:" + executor.getActiveCount());try {countDownLatch.await();} catch (InterruptedException e) {e.printStackTrace();}System.out.println("开始检测线程池中线程数量");while (true) {Thread.sleep(1000);System.out.println("poolSize:" + executor.getPoolSize());System.out.println("core:" + executor.getCorePoolSize());System.out.println("活跃:" + executor.getActiveCount());System.out.println("======");}}
}
poolSize:9
core:5
活跃:9开始检测线程池中线程数量
poolSize:1
core:5
活跃:0
==================
poolSize:0
core:5
活跃:0
==================
poolSize:0
core:5
活跃:0
==================
可以看到,当设置为ture时,线程池中的任务都执行完后,线程池中的线程数量是0,因为核心线程也都被回收了。
如果将其设置为false呢,执行结果如下
poolSize:9
core:5
活跃:9
开始检测线程池中线程数量
poolSize:5
core:5
活跃:0
======
poolSize:5
core:5
活跃:0
======