看了几次,今天看到同事写的类似于这个executorService的模式的例子,又看了下,简单记录下
ThreadPoolExecutor参数
int corePoolSize 线程池基本大小
int maximumPoolSize 线程池最大大小
long keepAliveTime 线程保持活动时间,超过这个时间线程不作保留
TimeUnit unit 线程保持活动时间单位
BlockingQueue workQueue 工作队列
ThreadFactory threadFactory 线程工厂
RejectedExecutionHandler handler 驳回回调
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
//工作的线程数<核心线程数
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
//线程都在运行&&此时没有线程再来管任务,任务只好进入workQueue
if (isRunning(c) && workQueue.offer(command)) {
//进入队列的这段时间,再次确认下是不是所有的线程都在运行
int recheck = ctl.get();
// !isRunning(recheck) 线程池没有运行 && 移除刚刚加入的任务
if (! isRunning(recheck) && remove(command))
//执行拒绝策略
reject(command);
//工作的线程数为0
else if (workerCountOf(recheck) == 0)
//null,false 只是启动一个线程
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;
//cas成功,表示ctl计数worker的个数+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 {
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());
/*
private static final int RUNNING = -1 ;
private static final int SHUTDOWN = 0 ;
private static final int STOP = 1 ;
private static final int TIDYING = 2 ;
private static final int TERMINATED = 3 ;
*/
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) {
//启动线程,workerStarted is true
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//task为null getTask()取值也为null,则线程跳出循环,线程终止
//实际上线程都是靠getTask()去阻塞的,也就是靠阻塞队列去阻塞
//workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) 在相对应的时间内如果拿不到任务,则会退出
//是否允许核心线程退出,通过设置allowCoreThreadTimeOut 变量
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);
}
}