连续execute()5个任务

1.1. 配置

var threadPool2 = new ThreadPoolExecutor(2, 3, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(2),
                new UserThreadFactory("MBinPC"), new UserRejectHandler());
复制代码

2. 题目/答案

配置如上的线程池,核心线程数为2,最大线程数为3,工作队列容量为2,问连续execute()5个任务会怎么样?

for (int i = 0; i < 5; i++) {
    threadPool2.execute(new Task());
}
复制代码

最后在人工调试干预下:

istarwyh-MBinPC-utf-1
Thread[istarwyh-MBinPC-utf-1,5,main]-执行任务
istarwyh-MBinPC-utf-2
Thread[istarwyh-MBinPC-utf-2,5,main]-执行任务
Thread[istarwyh-MBinPC-utf-1,5,main]-执行任务
Thread[istarwyh-MBinPC-utf-2,5,main]-执行任务
Thread[istarwyh-MBinPC-utf-1,5,main]-执行任务
复制代码

正常运行结果:

istarwyh-MBinPC-utf-1
istarwyh-MBinPC-utf-2
istarwyh-MBinPC-utf-3
Thread[istarwyh-MBinPC-utf-1,5,main]-执行任务
Thread[istarwyh-MBinPC-utf-2,5,main]-执行任务
Thread[istarwyh-MBinPC-utf-3,5,main]-执行任务
Thread[istarwyh-MBinPC-utf-1,5,main]-执行任务
Thread[istarwyh-MBinPC-utf-2,5,main]-执行任务
复制代码

这应该是因为正常运行execute()提交任务的速度大于任一线程执行完firstTask再去workQueue中拿线程的速度,因此队列满的情况下又建了一个线程。因为线程池的主要处理流程如下:

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享