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

85 阅读2分钟

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

线程池使用SynchronousQueue队列,执行任务大于corePoolSize,并且大于maximumPoolSize

线程池使用SynchronousQueue队列,执行任务线程数量大于核心线程,并且大于maximumPoolSize最大线程数

实现代码如下:

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<Runnable>());
        for (int i = 0; i < 7; 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 在执行时间: 1654569992255
pool-1-thread-2 在执行时间: 1654569992255
pool-1-thread-4 在执行时间: 1654569992257
pool-1-thread-3 在执行时间: 1654569992257
pool-1-thread-6 在执行时间: 1654569992260
pool-1-thread-5 在执行时间: 1654569992261
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task com.ozx.concurrentprogram.executor.controller.CorePoolSizeRun$1@4fccd51b rejected from java.util.concurrent.ThreadPoolExecutor@65e579dc[Running, pool size = 6, active threads = 6, queued tasks = 0, completed tasks = 0]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
	at com.ozx.concurrentprogram.executor.controller.CorePoolSizeRun.main(CorePoolSizeRun.java:31)

从运行结果看出,线程池执行最大线程数的任务数,其他任务则不再处理抛出异常,符合线程池五种中第五种。