Java 线程池
线程的创建是需要在JVM中开辟虚拟机栈、本地方法栈、程序计数器等线程私有的内存空间,在销毁时则需要回收这些资源,频繁地创建和销毁线程会浪费大量的系统资源,增加并发风险。线程池来管理线程的开销能很好地预防风险,同时可以更加充分合理地协调利用CPU、内存、网络、I/O等系统资源。
线程池 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.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
从上述代码得出,线程池核心参数有corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler; 每个参数的含义并不相同,并且有着至关重要的工作职责。
参数介绍
corePoolSize:在线程池中保持活动状态的核心线程数量,最小值是0;
maximumPoolSize:线程池能容忍的最大线程数;
keepAliveTime:空闲线程等待工作的超时时间;大于corePoolSize的空闲线程超过该时间会被回收,allowCoreThreadTimeOut为true时核心线程数也会被回收;
unit:超时时间的单位;
workQueue:线程池中保留任务并移交给工作线程的队列;
threadFactory:线程池中创建新的线程工厂;
RejectedExecutionHandler:在执行饱和或关闭时调用的拒绝策略执行;
线程池执行线程的过程描述代码如下(查看各参数如何工作):
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
1、判断执行线程是否为空,为空的情况就直接抛出空指针;
2、判断线程池当前工作线程是否小于coreSize,是则增加工作线程;
增加工作线程的过程:
1.如果当前线程池的运行状态是shutdown,并且当前任务为空,工作队列也为空,则创建过工作线程失败;
2.循环增加工作线程数量,如果当前工作线程大于活跃线程数,添加失败,否则直到添加成功跳出循环;
3.创建工作线程,通过线程工厂去创建工作线程;
4.工作线程创建成功直接start,失败则将工作线程数量恢复;
3、判断当前线程池是否处于运行状态并且工作队列能够继续添加线程,能则添加工作线程至队列;
4、如果等待队列也满了,则线程池的数量是否大于最大线程,不大于则开启工作线程,大于或等于则根据拒绝策略进行拒绝;
构造器解析
线程池提供了4个构造器进行线程池的初始化;
1、7个参数,6个参数有两个构造器,分别提供了ThreadFactory、RejectedExecutionHandler默认值,5个参数
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {...}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {...}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {...}
ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue){...}
也就是说在创建线程池过程中,真实核心的参数有5个,可调控的参数有7个。
BlockingQueue(阻塞队列):JDK自身就有很多,像ArrayBlockingQueue、LinkedBlockingQueue等其他队列信息。
ThreadFactory(线程工厂):主要功能就是创建Thread 线程的,所有Thread信息都可在这个工厂类去实现,JDK提供了默认的DefaultThreadFactory;
RejectedExecutionHandler(拒绝执行策略):ThreadPoolExecutor自己内部提供了4个策略分别是CallerRunsPolicy(调用任务的run方法绕过线程池直接执行)、AbortPolicy(丢弃任务并抛出RejectExecutionException 异常)、DiscardPolicy(丢弃任务,但是不抛出异常)、DiscardOldestPolicy(抛弃队列中等待最久的任务,然后把当前任务加入队列中),默认使用AbortPolicy;