【并发编程】- 线程池设置过期时间

552 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第15天,点击查看活动详情

线程池设置过期时间

KeepAliveTime:当执行任务大于corePoolSize值时,在没有超过指定时间内是不从线程池中将空闲线程删除,如果超过设置好的超时时间,则删除空闲线程,如果为0则任务执行完毕后立即从队列中删除。

实现代码如下:

public class CorePoolSizeRun {
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+" 在执行时间: "+System.currentTimeMillis());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 6, 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
        for (int i = 0; i < 6; i++) {
            threadPoolExecutor.execute(runnable);
        }
        try {
            Thread.sleep(100);
            System.out.println("第一阶段线程池核心线程数:"+threadPoolExecutor.getCorePoolSize());
            System.out.println("第一阶段线程池最大线程数:"+threadPoolExecutor.getMaximumPoolSize());
            System.out.println("第一阶段线程池活跃的线程数:"+threadPoolExecutor.getPoolSize());
            System.out.println("第一阶段线程池队列中任务数:"+threadPoolExecutor.getQueue().size());
            Thread.sleep(1000);
            System.out.println("第二阶段线程池核心线程数:"+threadPoolExecutor.getCorePoolSize());
            System.out.println("第二阶段线程池最大线程数:"+threadPoolExecutor.getMaximumPoolSize());
            System.out.println("第二阶段线程池活跃的线程数:"+threadPoolExecutor.getPoolSize());
            System.out.println("第二阶段线程池队列中任务数:"+threadPoolExecutor.getQueue().size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行结果如下:

第一阶段线程池核心线程数:5
第一阶段线程池最大线程数:6
第一阶段线程池活跃的线程数:6
第一阶段线程池队列中任务数:0
第二阶段线程池核心线程数:5
第二阶段线程池最大线程数:6
第二阶段线程池活跃的线程数:5
第二阶段线程池队列中任务数:0

从运行结果看出6个最大线程数,因为设置超过时间为0L,线程执行完毕后立即将空闲的线程从非corePool中删除,线程保留下核心线程数。