自定义线程池时的几个参数应该大家都挺熟悉,使用自定义线程池时,一般会设置线程超时时间,当超过核心线程数的线程空闲到我们指定的时间后,会释放空闲线程
以下面线程池为例:
ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 5,
5L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1));
当线程池因为任务的不断提交,线程池达到5个后,等任务执行完成,没有新的任务提交到此线程池,则在5秒后,线程数会回到3个,以达到减少服务内线程数的目的,减少内存和cpu的消耗,这3个线程可以称为 常驻核心线程;
那如果我们的业务场景不需要核心线程一直常驻,可以接受有需要的时候核心线程临时创建,在此期间大批量的业务能复用新创建的线程即可,平时没业务使用线程池的时候,线程池内没有任何线程该怎么做呢?
这时候我们就可以使用allowCoreThreadTimeOut这个属性,当此字段设置为true的时候,空闲线程在达到我们设置的空闲时间后,也会释放,即上面例子中的线程池,最终不仅会释放 5-3 个核心线程以外的线程,3个核心线程也会释放,即剩余0个线程。
测试代码:
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor allowCoreThreadTimeOutExecutor = new ThreadPoolExecutor(3, 5,
5L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1));
for (int i = 0; i < 6; i++) {
int finalI = i;
allowCoreThreadTimeOutExecutor.submit(() -> System.out.println("*****************" + finalI));
}
Thread.sleep(1000L);
System.out.println("已经达到最大线程数 " + allowCoreThreadTimeOutExecutor.getPoolSize());
Thread.sleep(6000L);
System.out.println("不设置 allowCoreThreadTimeOutExecutor为true,默认为false时,当线程池空闲,回收线后剩余的 线程数 " + allowCoreThreadTimeOutExecutor.getPoolSize());
System.out.println();
allowCoreThreadTimeOutExecutor.shutdown();
ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 5,
5L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1));
executor.allowCoreThreadTimeOut(true);
for (int i = 0; i < 6; i++) {
int finalI = i;
executor.submit(() -> System.out.println("*****************" + finalI));
}
Thread.sleep(1000L);
System.out.println("已经达到最大线程数 " + executor.getPoolSize());
Thread.sleep(6000L);
System.out.println("设置allowCoreThreadTimeOutExecutor为true,当线程池空闲,回收线后剩余的 线程数 " + executor.getPoolSize());
executor.shutdown();
}
执行结果: