线程池二
线程池详解二
接上一章,直接来看ThreadPoolExecutor 的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、首先是判断command 是否为空,为空则抛出异常。然后判断线程池里的线程是否少于corePoolSize 若小于则开启一个新的线程并将其作为该线程的firstTask执行。
来看看addWorker(command,true) 这个方法
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
//再次判断线程池的状态
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
//再判断线程池的当前线程数目是否大于corePoolSize
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
//当前线程数目+1
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 {
//将当前执行任务封装到worker类里面
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;
}
可以看到此方法有个核心的类Worker 来看看这个类,可以看到其实现了Runnable接口
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
其包装了一个Runnable 方法,并创建了一个Thread线程。来看看其实现的run() 方法
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//重点在这个getTask() 里面
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);
}
}
可以看出其是一个执行一个调用默认Task的run方法,
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// 判断这个Worker 是否一直存活,允许coreThread timeout 或者这个不是coreThread
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
//阻塞在这里,或者timeOut
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
从这里获取到Task,若无task则执行processWorkerExit(Worker w,boolean completedAbruptly) 进行销毁Worker.
注意最后并检测corePoolSize 是否是0,若为0,且workQueue不为空,则再开启一个线程进行执行。
总结一下
1、判断当前worker数量是否小于corePoolSize,若小于则开启一个worker进行执行任务,任务执行完毕后,这个是属于coreThread,默认一直阻塞在queue.take() 方法处,获取任务。
除非允许销毁coreThread 才会使用queue.poll(timeOut) 根据KeepAliveTime 允许线程在没有任务下的存活时间。从这个地方可以看出,其任务都是Worker在自动获取的。
并没有分配任务的功能。这种机制省了一个分配线程。
2、若不小于corePoolSize的话,则执行先判断pool的存活状态,若存活则加入到缓存队列。然后再判断是否存活,若存活在继续判断当前worker数目是否为0。
若为0则开启一个没有第一个任务的worker。去执行缓存队列的任务。并在没有任务的时候将worker销毁。
3、假如缓存队列,若加入不成功,则开启一个worker执行。(主要是队列是SynchronousQueue,此队列加入的同时,必须有线程在取数据,否则加入失败。)
常用的线程池创建
1、corePoolSize 为0,maxPoolSize为Integer.MAX_VALUE,queue为SynchronousQueue,线程创建后执行完任务后的存活时间是60S
Executors.newCachedThreadPool();
2、corePoolSize 为1,maxPoolSize 也为1,queue为LinkedBlockingQueue。
Executors.newSingleThreadExecutor();
3、corePoolSize 和maxPoolSize相同的
Executors.newFixedThreadPool(100);
4、这是个能做定时任务的线程池
Executors.newScheduledThreadPool(100);