持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第11天,点击查看活动详情
线程池执行任务数大于corePoolSize核心线程数,小于等于最大线程数
线程池使用LinkedBlockingDueue队列,任务数量大于corePoolSize时将其余的任务放到队列中。
实现代码如下:
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(4, 6, 5, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>());
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 在执行时间: 1654153872595
pool-1-thread-3 在执行时间: 1654153872595
pool-1-thread-1 在执行时间: 1654153872595
pool-1-thread-4 在执行时间: 1654153872596
第一阶段车中可载人的标准人数:4
第一阶段车中可在人的最大人数:6
第一阶段车中正在载的人数:4
第一阶段扩展车中正在载的人数:1
pool-1-thread-1 在执行时间: 1654153873603
第二阶段车中可载人的标准人数:4
第二阶段车中可在人的最大人数:6
第二阶段车中正在载的人数:4
第二阶段扩展车中正在载的人数:0
从运行结果看出指定5个任务要执行,而线程池核心线程数为4,所以一个任务暂时放入队列中,等待核心线程执行完其他任务,继续执行执行放入队列的任务。