FixedThreadPool为什么在还没有创建给定的核心线程数的时候就开始对线程进行重用?

w_okbuok_w 2019-08-20 05:15:39




图上显示,在第5个线程执行打印任务时,居然调用的是线程1,按照corePoolSize的涵义,不是应该创建线程数达到5,才会考虑线程的重用吗??
...全文
206 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
求教小菜鸟 2021-12-27
  • 打赏
  • 举报
回复

public class ThreadTest {
public static void main(String[] args) {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
fixedThreadPool.submit(() -> {
System.out.println(Thread.currentThread().getName());
});
}
}
}
输出结果
pool-1-thread-1
pool-1-thread-2
pool-1-thread-5
pool-1-thread-4
pool-1-thread-3
pool-1-thread-8
pool-1-thread-9
pool-1-thread-7
pool-1-thread-10
pool-1-thread-6
从输出结果可以看出FixThreadPool每接收一个任务创建一个线程,直到达到核心线程数,只是并发线程执行顺序是不一定的。

qq_32771135 2019-08-21
  • 打赏
  • 举报
回复
其实这里涉及到并发,例如:在执行了前4个任务新建了4个核心线程,然后第5个任务进来,去创建第5个核心线程,第5个核心线程刚创建完成,这时第6个任务也进来了,然后它发现现在核心线程池已经是5个了,就从中随机获取一个来执行,并且比第5个任务先执行完成,就会出现上面的情况。 或者可以这么理解,假设第5个核心线程刚创建完成,但它执行的这个任务比较耗时比如1s,就会变成其它线程都执行完了,第5个启动的任务才执行完成,写个例子很容易看出来

for (int i=1;i<10;i++){
            int j = i;
            pool.execute(()-> {
                if (j==5){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            System.out.println(Thread.currentThread().getName()+"==="+ j);});
        }
        pool.shutdown();
console: pool-1-thread-1===1 pool-1-thread-2===2 pool-1-thread-3===3 pool-1-thread-4===4 pool-1-thread-1===6 pool-1-thread-2===7 pool-1-thread-1===9 pool-1-thread-3===8 pool-1-thread-5===5
w_okbuok_w 2019-08-21
  • 打赏
  • 举报
回复
原来如此
maradona1984 2019-08-20
  • 打赏
  • 举报
回复
你理解错了 如果让你实现个线程池,你会做这种毫无意义且拧巴的实现?

51,411

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧