用过java线程的同学都应该大致了解,在java中,为了合理使用线程以合理利用资源、提高吞吐率以及加快响应时间,通常会使用java线程池,因为线程池架构设计合理,比起自己创建线程可能花销巨大来讲,线程池是一个很好的选择。
作为一只喜欢研究源码的程序猿,就我所学,来讲讲java线程池是如何巩工作的。
一.4种线程池
首先,java线程池为我们量身定制了4中拿来即用的线程池:
1.newSingleThreadExecutor:
public static ExecutorServicenewSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}
2.newFixedThreadPool:
public static ExecutorServicenewFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}
3.newCachedThreadPool:
public static ExecutorServicenewCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
4. newScheduledThreadPool:
public static ScheduledExecutorServicenewSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}
可以发现:除了newScheduledThreadPool,其他三个都是ThreadPoolExecutor的一种特殊实现。
二.ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue 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;
}
1.构造函数参数说明:
1).corePoolSize:线程池中的核心线程数
2).maximumPoolSize:线程池中的最大线程数
3).keepAliveTime: 线程池中的线程的存活时间
4).unit: keepAliveTime的时间单位
5).workQueue: BlockingQueue的实现,用于存储任务
6).threadFactory:自定义线程的创建工厂
7).handler:线程池的饱和策略,当阻塞队列满了,且没有空闲的线程,继续提交任务时,必须进行处理,默认的方式是抛出RejectedExecutionHandler异常
2.内部状态变量说明:
jdk1.8就是用一个int型来表示线程池的运行状态和运行任务数量,一个int一共32位,前3位表示运行状态,后29位表示运行任务线程数;运行状态和运行任务线程数量分别通过runStateOf(int c)和workerCountOf(int c)来获取,都是通过&操作来计算的。各个值的初始值分为如下:
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
// runState is stored in the high-order bits
private static final int RUNNING = -1 << COUNT_BITS;
private static final int SHUTDOWN = 0 << COUNT_BITS;
private static final int STOP = 1 << COUNT_BITS;
private static final int TIDYING = 2 << COUNT_BITS;
private static final int TERMINATED = 3 << COUNT_BITS;
// Packing and unpacking ctl
private static int runStateOf(int c) { return c & ~CAPACITY; }
private static int workerCountOf(int c) { return c & CAPACITY; }
private static int ctlOf(int rs, int wc) { return rs | wc; }
1).ctl:包装任务状态和线程数(高3位表示运行状态,后29位表示运行任务线程数),初始值:11100000000000000000000000000000,没多一线程就加1,为原子操作;默认AtomicInteger,如果数量不够的话,可以自行改成AtomicLong
2).COUNT_BITS:29
3).CAPACITY:运行任务线程数,值为:000 11111111111111111111111111111
4).RUNNING:运行状态, 值为:111 00000000000000000000000000000
5).SHUTDOWN:关闭状态, 值为:0
6).STOP: 停止状态, 值为:001 00000000000000000000000000000
7).TIDYING:整理状态, 值为:010 00000000000000000000000000000
8).TERMINATED:终止状态,值为:011 00000000000000000000000000000
3.内部公用函数说明:
1).runStateOf(int c):获取运行状态,
2).workerCountOf(int c):获取运行任务线程数
3).ctl(int rs,int wc): 包装运行状态和任务线程数
4).runStateLessThan(int c,int s):是否小于某个状态
5).runStateAtLesat(int c,int s):是否大于或者等于某个状态
这些公共函数接下来都会用到,写在这里是便于理解。
4.提交任务函数:execute(Runnable command)
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);
}
1).如果当前运行任务线程数小于corePoolSize,尝试另起线程去运行任务。调用addWorker函数会自动检查运行状态和运行任务线程数,防止添加线程时出现多线程操作错误。
2).如果添加新的线程失败,那么就将该任务添加到队列中,同时,还需要检查运行状态和运行任务线程数;再次检查状态,防止入列期间出现状态改变情况,如果线程池处于非运行状态,移除任务;如果没有运行任务线程数量为0,则起一个新的线程。
3).如果任务不能进入队列(例如队列满了),再次尝试另起一个线程运行;如果失败了,使用拒绝策略。
5.addWorker
在execute函数中,addWorker是另起线程去执行任务,它的具体实现如下:
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;
}