赞
踩
ThreadPoolExector实际上就是一个生产消费模式,当调用execute()方法添加任务线程时,相当于生产者生产数据元素,workers线程池中的线程执行任务线程或从阻塞队列中获取任务线程执行时,相当于消费者消费数据元素。
1)、线程池中的线程是什么样的线程对象?
2)、线程池中的线程用什么来进行存储?
3)、处于等待状态的任务线程又放在那里?
4)、线程池中的线程是如何获取并执行这些处于等待状态中的任务线程的?
首先区分一下任务线程和线程池中的线程,任务线程就是调用execute(Runnable command)方法中的command线程。而线程池中的线程是一个个的Worker对象。而这些Worker对象存放在workers属性中。
- //workers用来存放线程池中的线程
- private final HashSet<Worker> workers = new HashSet<Worker>();
处于等待状态中的任务线程会存放到workQueue中
- //存放处于等待状态的任务线程
- private final BlockingQueue<Runnable> workQueue;
执行等待中的线程会在Work类中的runWorker()方法进行,会在后面进行讲解
execute()方法的作用时把任务线程提交到线程池,由线程池来执行该任务线程。
源码如下:
- public void execute(Runnable command) {
- if (command == null)
- throw new NullPointerException();
- int c = ctl.get();
- //workerCountof(c)获取运行状态的线程数
- if (workerCountOf(c) < corePoolSize) {
- if (addWorker(command, true))
- return;
- c = ctl.get();
- }
- //isRunning(c)判处线程池处于运行状态。
- 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);
- }

分析execute()方法需要考虑两种情况,一种是corePoolSize大于0的情况,一种是corePoolSize等于0的情况。这里只对ThreadPoolExector如何实现生产消费模式进行分析,而状态只是确保线程池线程的正常运行,这里不进行分析讲解,所以选择忽略来提取骨干代码分析说明。
当corePoolSize大于0,忽略状态分析后的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;
- //......
- }
- //第二种场景
- if (isRunning(c) && workQueue.offer(command)) {
- //........
- }
- //第三种场景
- else if (!addWorker(command, false))
- reject(command);
- }

可以分为在三种不同场景下使用execute()方法提交任务线程的处理方式。
第一种场景:当线程池中正在运行的线程数量小于corePoolSize(核心线程数量)时,调用execute()方法添加任务线程的场景,处理方式是,调用addWorker()方法,往线程池workers中添加Worker线程,并执行任务线程,下面会对addWoker()方法进行说明。
第二种场景:当线程池中正在运行的线程数量等于corePoolSize(核心线程数量)时,调用execute()方法添加任务线程的场景。处理方式是,直接调用workQueue.offer(command)往阻塞队列中添加任务线程。
第三种场景:当线程池中正在运行的线程数量等于corePoolSize,且workQueue阻塞队列队满的情况下,调用execute()方法添加任务线程的场景。处理方式是,直接调用饱和策略对该任务线程进行处理。
boolean addWorker(Runnable firstTask, boolean core):往线程池workers种添加Worker线程,并启动Worker线程
源码如下:
- 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 {
- 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;
- }

忽略状态状态分析,提取骨干代码如下:
- private boolean addWorker(Runnable firstTask, boolean core) {
- //第一部分
- retry:
- for (;;) {
- //....忽略.....
- for (;;) {
- //...忽略....
- if (compareAndIncrementWorkerCount(c))
- break retry;
- //....忽略...
- }
- }
- //第二部分
- 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 {
- int rs = runStateOf(ctl.get());
-
- if (rs < SHUTDOWN ||(rs == SHUTDOWN && firstTask == null)) { //这里的直接看成true就可以了
- //......
- //把线程添加到线程池
- workers.add(w);
- //....
- }
- } finally {
- mainLock.unlock();
- }
- if (workerAdded) {
- //启动该线程
- t.start();
- workerStarted = true;
- }
- }
- } finally {
- //把worker线程添加到线程池失败的处理场景
- if (! workerStarted)
- addWorkerFailed(w);
- }
- return workerStarted;
- }

忽略状态后,可以把addworker()分为两部分
第一部分:调用CAS方法给正在运行的线程数量加1,但worker线程还没有启动执行
第二部分:主要可以分为如下三个步骤
1)、使用传入的任务线程创建worker线程
2)、把worker线程添加到workers线程池中
3)、启动该worker线程。
上面已经的addWorker()方法已经启动Worker线程,那接下分析Worker线程的run方法。源码如下:
- public void run() {
- runWorker(this);
- }
源码如下:
- 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);
- }
- }

忽略状态处理和部分异常提取骨干代码如下:
- final void runWorker(Worker w) {
- //....
- Runnable task = w.firstTask;
- // ...
- try {
- while (task != null || (task = getTask()) != null) {
- w.lock();
- // ....
-
- try {
- //..执行任务线程前干一些事情
- beforeExecute(wt, task);
- Throwable thrown = null;
- try {
- //任务线程执行
- task.run();
- }
- //...忽略异常..
- } finally {
- //执行任务线程后干一些事情
- afterExecute(task, thrown);
- }
- } finally {
- //任务线程设置为null
- task = null;
- w.completedTasks++;
- w.unlock();
- }
- }
- completedAbruptly = false;
- } finally {
- processWorkerExit(w, completedAbruptly);
- }
- }

骨干代码分析:这里主要关注的是while循环中的代码。
while第一次循环的时候,执行的任务线程是在第一种场景也就是线程池中正在运行的线程数量小于corePoolSize时调用execute()方法传入的任务线程,之后的每次循环执行都是调用getTask()方法获取到的阻塞队列workQueue中的任务线程。
每次任务线程结束,task都会设置为null,是为了能够调用getTask()方法获取任务线程。
getTask()方法的骨干代码如下:
- private Runnable getTask() {
- boolean timedOut = false; // Did the last poll() time out?
- for (;;) {
- //......
- // 队列为空时返回null,忽略状态判断
- if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
- decrementWorkerCount();
- return null;
- }
- //获取timed的值
- int wc = workerCountOf(c);
- boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
- //......
-
- try {
- //根据timed获取阻塞队列中任务线程
- Runnable r = timed ?
- workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
- workQueue.take();
- if (r != null)
- return r;
- timedOut = true;
- } catch (InterruptedException retry) {
- timedOut = false;
- }
- }
- }

忽略状态分析getTask()方法,大致可以分为三个步骤
1、如果阻塞队列workQueue中没有任务线程,返回null
2、获取timed的值时true还是false,allowCoreThreadTimeOut的初始值为false,而当corePoolSize的值大于0时,调用getTast()方法时正在运行的线程只能是等于或者小于corePoolsize的值,所以当corePoolSize的值大于0时,timed的值为false。
3、根据timed获取阻塞队列workQueue中的任务线程。当corePoolSize的值大于0时,timed的值为false,所以使用take()方法获取阻塞队列中的值。
这只是个人的理解和分析,如果有不正确的地方麻烦留言指正
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。