【并发编程】- 线程池使用SynchronousQueue队列,执行任务大于核心线程数

231 阅读2分钟

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

线程池使用SynchronousQueue队列,执行任务数大于corePoolSize核心线程数,小于等于最大线程数

线程池队列使用SynchronousQueue,任务数量大于corePoolSize核心线程数,将其余的任务放入池中,线程总数量没有超过最大线程数,运行的线程数为6,数量上大于corePoolSize核心线程数,所以KeepAliveTime大于5秒后清除空闲线程,因此使用SynchronousQueue队列,maximunPoolSize参数能起作用。

实现代码如下:

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, 5, TimeUnit.SECONDS, new SynchronousQueue<>());
        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(10000);
            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();
        }
    }
}

运行结果如下:

pool-1-thread-1 在执行时间: 1654504098762
pool-1-thread-2 在执行时间: 1654504098764
pool-1-thread-3 在执行时间: 1654504098764
pool-1-thread-4 在执行时间: 1654504098765
pool-1-thread-5 在执行时间: 1654504098765
pool-1-thread-6 在执行时间: 1654504098765
第一阶段线程池核心线程数:5
第一阶段线程池最大线程数:6
第一阶段线程池活跃的线程数:6
第一阶段线程池队列中任务数:0
第二阶段线程池核心线程数:5
第二阶段线程池最大线程数:6
第二阶段线程池活跃的线程数:5
第二阶段线程池队列中任务数:0

从运行结果看出指定6个任务要执行,而线程池核心线程数为5,使用SynchronousQueue队列,马上创建了6个线程分别执行6个任务,而不是将其余的任务放入队列中等待空闲的核心线程,超过指定时间后空闲线程被清理,保留对应的核心线程数。