线程是我们日常频繁使用到得一个东西,但是频繁创建线程会增加系统资源得消耗,为了解决这一个问题,于是聪明得程序员们创造了线程池这样一个数据结构。其基本思想就是,初始化线程池得时候,会预先生成好几条线程,存放在线程池中,当有任务进来得时候,工作线程就会启动,处理任务。没有任务,那么线程就会进入休眠状态,当一段时间没有任务需要处理,那么工作线程就会被销毁掉。

在java中线程池的实现就是ThreadPoolExecutor,本章我们要重点分析一下这个线程池的基本参数和构造,这也是面试经常问到的问题之一,首先来看一下这个类的集成结构:

java常见面试题-ThreadPoolExecutor构造函数参数解析

可以看到这个类是实现了Executor接口,这个接口定义了线程池的基本操作:

void execute(Runnable command);

这个方法即执行任务的方法,接收的参数是Runnable的实现类。下边我们来重点分析一下ThreadPoolExecutor的构造方法的几个参数:

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

通过源码我们可以看到ThreadPoolExecutor有好几个构造函数,但是最终都会调用这个构造函数,那么我就那最全的一个分析吧。

  1. corePoolSize :线程池中会常驻corePoolSize 条工作线程,除非用户设置了allowCoreThreadTimeOut,否则它们是不会怠工的。

  2. maximumPoolSize :线程池允许最多的线程数

  3. keepAliveTime:当工作线程大于最大允许的线程数的时候,任务的存活时间

  4. unit :keepAliveTime的时间单位

  5. workQueue:设置线程池的工作队列

  6. threadFactory :用于创建新线程的线程工厂

  7. handler:当任务被线程池拒绝的时候处理类

 

相关文章:

  • 2021-08-03
  • 2022-01-12
  • 2022-12-23
  • 2021-05-12
  • 2022-12-23
  • 2022-12-23
  • 2021-11-06
猜你喜欢
  • 2021-07-12
  • 2022-12-23
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
  • 2021-09-30
  • 2021-08-18
相关资源
相似解决方案