共计 1758 个字符,预计需要花费 5 分钟才能阅读完成。
下面是提交了工作后,线程池解决流程。如果想在工作提交前预热线程池能够应用 prestartAllCoreThreads 提前创立线程。
须要留神的是,上图中两个中央的创立线程都是须要加锁的,相干代码如下图:
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 {
// 这里的外部类 Worker 继承了 AbstractQueuedSynchronizer,也实现了 Runnable
//Worker 外面有个 Thread 属性,每次创立工作的时候都会对应创立一个线程
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;
}
这里再列一下几种工作队列:
- ArrayBlockingQueue: 基于数组构造的有界阻塞队列,队列按 FIFO 准则对元素进行排序。
- LinkedBlockingQueue: 基于链表构造的阻塞队列,同样按 FIFO 准则排序,吞吐量通常高于 ArrayBlockingQueue。
- SynchronousQueue: 自身不存储元素的阻塞队列,每次插入须等到另一个线程调用移除操作,否则插入操作会始终阻塞,吞吐量要高于 LinkedBlockingQueue。
- PriorityBlockingQueue: 具备优先级的有限阻塞队列。
几种饱和策略:
- AbortPolicy:间接抛出异样
- CallerRunsPolicy:应用调用者所在线程运行
- DiscardPolicy:抛弃队列里最近的一个工作,并执行当前任务
- dISCARDPolicy:不解决,抛弃掉
当然也能够实现 RejectedExecutionHandler 接口自定义策略进行解决。
正文完