Java多线程系列(补充一)核心线程与普通线程区别

本文深入探讨了核心线程与普通线程在Java线程池中的关键区别,核心线程在idle状态时会被保留,而非核心线程则会被回收。分析了不同线程池类型的核心线程数设置及工作队列类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本系列作为多线程系列的补充

核心线程与普通线程区别,这个问题之前没有注意到过,最近面试被问,所以就单独写个文章分析下

其实这个也非常简单了

构造线程池的时候Executors.newxxx的方法,点进去,会发现内部是通过

     /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default thread factory and rejected execution handler.
     * It may be more convenient to use one of the {@link Executors} factory
     * methods instead of this general purpose constructor.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

这个构造方法来做的

再看下super

 /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} or {@code handler} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

我们这里一个参数一个参数的来看

第一个参数:corePoolSize  这个就是我面试被问的关键点了,其实就是核心线程在idle的时候会被keep,而普通的线程不会。

第二个参数:maximumPoolSize,最大线程数。

第三个参数:

              keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.

翻译一下就是:如果池内线程数大于core线程数,切这个时候多余的线程是idle的,则等多久terminating

第四个参数:unit 是秒啊,还是分钟,小时

第五个参数 workqueue  这个不同的线程池类型有不同类型的queue,比如

newSingleThreadExecutor:LinkedBlockingQueue
newFixedThreadPool:LinkedBlockingQueue
newCachedThreadPool:SynchronousQueue
newScheduledThreadPool:DelayedWorkQueue

另外:对于 newWorkStealingPool 使用的是ForkJoinPool

ForkJoinPool运用了Fork/Join原理,使用“分而治之”的思想,将大任务分拆成小任务分配给多个线程执行,最后合并得到最终结果,加快运算。

第六个参数:threadFactor 就是Thread的工厂类,提供thread的

第七个参数: 

              handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached

当线程边界或者队列容量达到上限时的处理类。。

=====================================================================

总结一下这里面的要点

1.核心线程idle的时候不会被回收,非核心线程会被回收  (当然,可以用 allowCoreThreadTimeOut来配置)

2.关于核心线程数:

newCachedThreadPool   0个

newSingleThreadExecutor 1个

newFixedThreadPool 看参数

newScheduledThreadPool 看参数个数

3.不同的线程池有不同的queue

 

 

 

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值