概念
线程池是一种线程使用的管理策略,它创建一定数量的线程,并在需要时重复使用这些线程,而不是每次都创建和销毁线程。线程池可以有效地减少资源消耗,提高响应速度,并允许更好的线程管理。
继承关系
结构分析
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
:线程池中核心线程数的数量。maximumPoolSize
:线程池中允许创建线程的最大数量。keepAliveTime
:这个参数代表允许线程处于空闲的时长。TimeUnit
:超时时间单位workQueue
:等待线程执行的阻塞队列
BlockingQueue
ArrayBlockingQueue
LinkedBlockingQueue
SynchronousQueue
threadFactory
:线程工厂handler:任务满时处理器
AbortPolicy:丢弃任务并且抛出一个异常:RejectedExecutionException
CallerRunsPolicy:如果调用线程没有被关闭,那么就由调用线程来处理
DiscardOldestPolicy:丢弃最老的未处理任务,尝试执行新任务
DiscardPolicy:丢弃任务不处理,不抛出异常
评论区