持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第13天,点击查看活动详情
线程池使用LinkedBlockingDueue队列,执行任务数大于maximumPoolSize
线程池使用LinkedBlockingDueue队列,执行任务数大于corePoolSize核心线程数,大于maximumPoolSize最大线程数,设置KeepAliveTime过期时间。
实现代码如下:
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 LinkedBlockingDeque<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 在执行时间: 1654506338166
pool-1-thread-2 在执行时间: 1654506338167
pool-1-thread-3 在执行时间: 1654506338168
pool-1-thread-4 在执行时间: 1654506338168
pool-1-thread-5 在执行时间: 1654506338169
第一阶段线程池核心线程数:5
第一阶段线程池最大线程数:6
第一阶段线程池活跃的线程数:5
第一阶段线程池队列中任务数:2
pool-1-thread-3 在执行时间: 1654506339181
pool-1-thread-5 在执行时间: 1654506339181
第二阶段线程池核心线程数:5
第二阶段线程池最大线程数:6
第二阶段线程池活跃的线程数:5
第二阶段线程池队列中任务数:0
从运行结果看出指定7个任务要执行,而线程池核心线程数为5,使用LinkedBlockingDeque队列,同一时间最多只能有corePoolSize个线程在运行,其余的任务放入队列中,等待空闲的核心线程来处理,所以keepAliveTime大于5秒,不清除空闲线程。