【并发编程】- 线程池使用SynchronousQueue队列

88 阅读2分钟

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

线程池使用SynchronousQueue队列、添加任务小于等于核心线程数

线程池使用了SynchronousQueue队列,并且任务线程数量小于等于corePoolSize,所以KeepAliveTime大于5时也不会清除空闲线程。

实现代码如下:

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 < 5; 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-2 在执行时间: 1654153267119
pool-1-thread-3 在执行时间: 1654153267119
pool-1-thread-1 在执行时间: 1654153267119
pool-1-thread-4 在执行时间: 1654153267122
pool-1-thread-5 在执行时间: 1654153267123
第一阶段车中可载人的标准人数:5
第一阶段车中可在人的最大人数:6
第一阶段车中正在载的人数:5
第一阶段扩展车中正在载的人数:0
第二阶段车中可载人的标准人数:5
第二阶段车中可在人的最大人数:6
第二阶段车中正在载的人数:5
第二阶段扩展车中正在载的人数:0

线程池创建了核心线程后,执行对应任务,没有销毁核心线程,而是在等待其他任务。