我们常用的线程池实现如:
ExecutorService fixdThreadPool = Executors.newFixedThreadPool(10);
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
是使用Executors类的方法创建的,他的内部创建了ThreadPoolExecutor对象,代码如下:
//FixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
//CachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
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;
}
corePoolSize属性代表的是线程池对象允许的最大空闲线程数
maximumPoolSize属性代表的是线程池对象所允许的最大的线程数
workQueue 对应的就是阻塞队列的实例
keepAliveTime 当创建的线程数大于corePoolSize的时候,任务执行完成之后线程就空闲了出来,此时多出corePoolSize大小的线程就要注销掉,这个参数就是指定如果在keepAliveTime 时间内没有新的任务执行的话线程就注销掉。
threadFactory 是用来创建线程的工厂类
handler 是对应的饱和策略处理类,当线程池创建的线程到达上限maximumPoolSize,同时往阻塞队列workQueue放入失败时就会调用饱和策略来处理
下面就FixedThreadPool线程池和CachedThreadPool线程池注意区分这说。
FixedThreadPool:
执行fixdThreadPool线程池的execute方法,执行代码如下:
fixdThreadPool.execute(new Runnable(){
@Override
public void run() {
System.out.println("aaaaa");
}
继续跟踪进入ThreadPoolExecutor的execute()方法:
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);
}
如果启动的线程数量小于这个corePoolSize的值,就调用addWorker(command, true)方法,addWorker(command, true)源码如下:
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 {
final ReentrantLock mainLock = this.mainLock;
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int c = ctl.get();
int rs = runStateOf(c);
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;
}
addWorker方法首先进入一个自旋的循环尝试将云心的线程数量加1
compareAndIncrementWorkerCount(c)
成功之后退出自旋接着往下执行,首先拿到final ReentrantLock mainLock = this.mainLock;锁对象往下执行
然后用一个Worker类包装了我们传入的Runnable对象,Worker实际上是线程执行的处理类,里面包装了thread对象和执行的任务,等下来分析Worker类
接下来mainLock.lock()上锁,将Runnable接口的包装类Worker放入名称为workers的HashSet集合中。最后释放锁对象。如果添加成功则调用Worker类的thread属性启动线程。
执行成功之后返回execute方法。如果这个workerCountOf(c) > corePoolSize就尝试放入阻塞队列中。
接下来的代码又调用了addWorker方法尝试新建线程执行,为什么要这样子设计呢,这里买下一个伏笔,下文讲解CachedThreadPool的SynchronousQueued的时候会解释:
else if (!addWorker(command, false))
reject(command);
如果执行失败调用reject(command);方法由我们定义的饱和策略来执行处理。
接下来说说Worker这个类的实现,上面分析过如果启动的线程数量小于这个corePoolSize的值就会调用addWorker(command, true)这个方法,这个方法通过
w = new Worker(firstTask);
创建了一个Worker类的实例,Worker类的代码如下,他也实现了Runnable接口:
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
/**
* This class will never be serialized, but we provide a
* serialVersionUID to suppress a javac warning.
*/
private static final long serialVersionUID = 6138294804551838833L;
/** Thread this worker is running in. Null if factory fails. */
final Thread thread;
/** Initial task to run. Possibly null. */
Runnable firstTask;
/** Per-thread task counter */
volatile long completedTasks;
/**
* Creates with given first task and thread from ThreadFactory.
* @param firstTask the first task (null if none)
*/
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
/** Delegates main run loop to outer runWorker */
public void run() {
runWorker(this);
}
// Lock methods
//
// The value 0 represents the unlocked state.
// The value 1 represents the locked state.
protected boolean isHeldExclusively() {
return getState() != 0;
}
protected boolean tryAcquire(int unused) {
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
protected boolean tryRelease(int unused) {
setExclusiveOwnerThread(null);
setState(0);
return true;
}
public void lock() { acquire(1); }
public boolean tryLock() { return tryAcquire(1); }
public void unlock() { release(1); }
public boolean isLocked() { return isHeldExclusively(); }
void interruptIfStarted() {
Thread t;
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
}
}
构造方法中将firstTask属性和thread属性初始化,firstTask就是我们execute方法中传入的任务,调用ThreadFactory创建Thread对象,逐一这里将this传入就是说这个Thread对象实际上要执行的实现
Runnable接口的任务就是这个Worker类自身,因为他也实现了Runnable接口,Worker类的run方法中调用了runWorker方法,将this对象传入,下面接着看ThreadPoolExecutor这个类的runWorker方法,方法
接受一个Worker对象,代码如下:
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
这个方法主要的逻辑就是首先判断firstTask是不是null不是的话要先执行firstTask,将他的引用保存在本地,将firstTask设置为null ,执行firstTask,执行完以后继续调用getTask方法,
getTask方法我们可以猜到就是从BlockingQueue阻塞队列中获取任务,BlockingQueue有多个子列实现,对于FixThreadPool的实现就是LinkedBlockingQueue,CachedThreadPool实现就是SynchronousQueue
我们依次分析一下这两个BlockingQueue的take方法。
LinkedBlockingQueue:
public E take() throws InterruptedException {
E x;
int c = -1;
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly();
try {
while (count.get() == 0) {
notEmpty.await();
}
x = dequeue();
c = count.getAndDecrement();
if (c > 1)
notEmpty.signal();
} finally {
takeLock.unlock();
}
if (c == capacity)
signalNotFull();
return x;
}
通过源码可以看出LinkedBlockingQueue是一个无界的链表数据结构存储的Queue,LinkedBlockingQueue采用ReentrantLock和Condition来实现同步,当队列为空时,线程就阻塞在这里。
SynchronousQueue:SynchronousQueue的take方法代码如下:
public E take() throws InterruptedException {
Object e = transferer.transfer(null, false, 0);
if (e != null)
return (E)e;
Thread.interrupted();
throw new InterruptedException();
}
他又调用了transferer.transfer来实现,我们看看transferer是个什么东东:
Transferer类是一个定义在SynchronousQueue内部的抽象类,只定义了一个transfer的抽象方法,他有两个实现类分别是TransferQueue,TransferStack。顾名思义就是队列和堆栈的实现。
在构造SynchronousQueue对象时,默认创建的就是TransferStack也就是堆栈数据结构的实现。
public SynchronousQueue() {
this(false);
}
public SynchronousQueue(boolean fair) {
transferer = fair ? new TransferQueue() : new TransferStack();
}
还记得线程池的execute方法在当前线程数小于corePoolSize大小时会调用addWorker方法,对于CacheThreadPool来说,他的corePoolSize大小为0,所以不会走addWorker方法,他会直接调用workQueue的offer往workQueue里面放,这个workQueue的实现就是SynchronousQueue队列,来看看他的offer方法
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
return transferer.transfer(e, true, 0) != null;
}
他也同样调用transferer.transferer方法,有点乱啊,offer和take同样调用的这个方法,但是传入的参数是不同的,
我们首先来分析take(为什么先看这个呢,等下你就知道了),他是从队列里面取Runnable任务:
他传入的参数是 transferer.transfer(null, false, 0),他有两个mode,根据传入的第一个参数,如果是null,mode就是REQUEST,如果不是null(就是Runnbale对象)mode就是DATA。
然后进入一个自旋的方法首先将head头结点赋值给一个临时变量,第一次take这个head肯定是null然后他就调用casHead(h, s = snode(s, e, h, mode))方法创建一个节点并设置为头结点。
if (h == null || h.mode == mode),如果head==null或者head不为空,但是新进入的线程的mode和head的mode相同,都会走这段的代码,也就是说多个线程在这里就形成了一个等待的链式结构,
接下来调用awaitFulfill方法跟踪代码可以看到
else if (!timed)
LockSupport.park(this);
的代码,恍然大悟,原来线程阻塞在这里,我们猜想SynchronousQueue这个队列存放的并不是用户提交的Runnable任务,而是排队的线程,如果
接下来看看看offer这个方法,传入的参数是transferer.transfer(e, true, 0)
mode的值就是DATA,如果当前的head是null的话,就直接返回null,回想一下我们讲解ThreadPool的execute方法的时候如果往队列里面放入失败的话又调用了一次addWorker方法,在这里就得到了印证,如果是
CachedThreadPool第一次提交任务,head肯定为空(也就是当前没有空闲的线程在等待)那么就返回null,提交失败,则再次调用addWorker方法尝试新建一个线程来处理。
如果head不为null也就是至少有一个线程阻塞在awaitFulfill方法中,那么offer方法就再创建一个SNode对象,将这个对象设置为head,然后拿到当前head的next和next的SNode对象,这个next就是等待的线程对象的SNode,
调用等待线程的SNode对象的m.tryMatch(s)方法,将当前的head的SNode对象传入,这个方法就是将线程的SNode对象的match属性设置为head的SNode对象然后调用LockSupport.unpark(w);将等待的线程对象唤醒,唤醒的线程就拿到自己的SNode对象的match属性返回,这样子阻塞的线程就拿到了用户提交的一个任务去执行,调用offer的线程再将头结点重新设置为刚释放的线程的SNode对象的next的SNode对象。