线程池工作流程
- 核心线程数 2.最大线程数 3.工作队列
当我们将任务丢给线程池时
首先检查线程数有没有达到了核心线程数
如果还没到,就直接开新线程
否则尝试塞进工作队列,没满就塞进去
如果工作队列满了就看线程数有没有达到最大线程数
如果没有就开新线程
(排队的人好多,处理不过来,找多个人来帮忙)
否则按饱和策略处理
(找不到人了,排队要很久,你自己看着办)
核心线程不是固定的几条,而是最后没死掉的几条,是动态变换的
Worker创建的时候会创建一个线程, 一个Woker对应一个线程
Woker将当前的runnable运行完后会从队列里取下一个runnable
设置的超时时间就是再poll队列的时候使用的
一旦超时就会标记超时,当线程数>核心线程数的时候,就通过CAS操作结束当前worker
当线程数<核心数 就会阻塞住 等待新的事件到达 (此时该Worker就是所谓的核心线程)
'https://blog.csdn.net/weixin_42112635/article/details/100419998
下面给出几个重要的方法
ctl 也是一个很重要的变量,他记录了两个东西,一个是线程池的状态,另外一个是worker的数量。
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);
}
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);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
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);
}
}