从源码看ThreadPoolExecutor(线程池)的参数

本文详细解析了Java中ThreadPoolExecutor的七个关键参数,包括核心线程数、最大线程数、空闲线程存活时间等,阐述了它们在自定义线程池时的作用与意义。

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

在jdk1.8的类ThreadPoolExecutor中创建有参的构造器。在下面的代码中展示了涉及到的参数。

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;
    }
    /**
     * 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
     */

但是有时候在面试的过程中,会问到你问到这些参数的意思。上面的注释就是对各个参数的解释,在接下来的过程中将分别解释线程池的7个参数。

  /**
     * 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

corePoolSize: 即使有些线程是闲置的,都要保持池中核心线程的数量,除非你设置了allowCoreThreadTimeOut参数

* @param maximumPoolSize the maximum number of threads to allow in the
     *        pool

maximumPoolSize:参数maximumPoolSize是在池中允许的最大线程数
 

* @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.

keepAliveTime(存活时间) :当某个线程的线程数远大于核心数时,在新任务中大量的空闲线程一直处于等待状态,那就回收它。 

* @param unit the time unit for the {@code keepAliveTime} argument

unit: keepAliveTime参数的时间单位

  * @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.

workQueue(存放待执行任务的队列):在任务执行之前提交任务到队列中使用。这个队列仅仅存放Runnable任务被execute方法提交。(又可以叫做存放处于等待状态线程的队列)

 * @param threadFactory the factory to use when the executor
     *        creates a new thread

threadFactory(线程工厂):创建线程时工厂开始使用。

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

handler(拒绝策略):当到达最大线程数或者是队列中都是任务时,提交的任务将会被阻塞,这时候就执行拒绝策略。

这篇文章主要讲线程池的7个参数,在下一篇文章中继续讲,当我们自定义一个线程池时,线程池的参数将如何设置。

 

线程池ThreadPoolExecutor)是 Java 中用于管理和执行线程的机制。下面是ThreadPoolExecutor源码的剖析: ```java public class ThreadPoolExecutor extends AbstractExecutorService { // 省略其他成员变量 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { // 根据参数创建线程池 } // 省略其他构造方法和方法重载 public void execute(Runnable command) { // 执行任务,将任务提交给线程池进行处理 } // 省略其他方法 private void runWorker(Worker w) { // 工作线程执行具体任务的逻辑 Runnable task = w.firstTask; w.firstTask = null; boolean completedAbruptly = true; try { while (task != null || (task = getTask()) != null) { // 执行任务 task.run(); task = null; } completedAbruptly = false; } finally { processWorkerExit(w, completedAbruptly); } } // 省略其他内部类和方法 } ``` 上述代码展示了ThreadPoolExecutor的主要结构。它是一个实现了ExecutorService接口的具体类,在Java中用于执行和管理线程池。 在构造方法中,我们可以设置核心线程数(corePoolSize)、最大线程数(maximumPoolSize)、空闲线程的存活时间(keepAliveTime)、时间单位(unit)和阻塞队列(workQueue)等参数。 execute方法用于向线程池提交任务,任务将被封装成一个Runnable对象,然后由线程池中的工作线程执行。 runWorker方法被工作线程调用,用于执行具体的任务逻辑。它不断地从阻塞队列中获取任务并执行,直到阻塞队列为空或工作线程被中断。 这只是ThreadPoolExecutor源码的简要剖析,了解更多细节可以查看源码实现。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值