前言
-
初次了解自定义线程池 ThreadPoolExecutor 的小伙伴,可以先看这篇文章:有界、无界队列对ThreadPoolExcutor执行的影响
-
allowCoreThreadTimeOut :方法作用:设置是否回收在保活时间后依然没没有任务执行核心线程。
举例
- 下面我们会通过 CountDownLatch 工具来验证这个线程池 allowCoreThreadTimeOut 问题
- CountDownLatch 一般称为闭锁、计数器,是一种多线程同步工具,属于 AQS 体系的一员。
- 如果你对 CountDownLatch 不了解,可以点击参考:并发工具类:等待多线程完成的 CountDownLatch,和 join 的区别
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("======");
}
}
}
结果分析
- 代码中的静态代码块中通过 executor.allowCoreThreadTimeOut(true)设置回收核心线程,执行结果如下:
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
======
- 线程池中的任务都执行完后,线程池中核心线程没有被回收。
总结
- 这个参数默认值为:false
- 设置成true还是false需要根据你具体的业务判断,如果该业务需要执行的次数并不多,采用多线程只是为了缩短执行的时间,那么可以设置成true,毕竟用完后很长时间才会用到,线程干耗着也是耗费资源的。
- 但是如果是需要较高并发执行的业务,那么可以设置为false,保留着线程,避免每次都得创建线程耗费资源。
- 声明:原文:https://blog.csdn.net/kusedexingfu/article/details/106879660