[JAVA学习笔记-71]ThreadPoolExecutor的execute原理

来源:互联网 发布:推广淘宝产品 编辑:程序博客网 时间:2024/06/06 04:12

原理综述:
ThreadPool 用一个Worker对象封装了用户指定的Runnable对象,同时Worker类实现了Runnable接口,Worker对象
将自己封装到一个Thread对象并保存在自身内部,ThreadPool将满足条件的Worker对象加入Workers的HashSet,并调用
Worker.start()启动Worker线程,Worker在run中会调用启动内部封装的Runnable对象。

【将Runnable对象提交给ThreadPool执行】
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true)) /true表示线程数的限制使用corePoolSize/
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);
}

【创建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))  /*这里的count使用了AtomicInteger*/                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 {        final ReentrantLock mainLock = this.mainLock;        /*将firstTask保存在Worker中,并将Worker封装到Thread对象中*/        w = new Worker(firstTask);        final Thread t = w.thread;   /*封装了Worker对象的Thread对象(Worker实现了Runnable接口)*/        if (t != null) {            mainLock.lock();            try {                // Recheck while holding lock.                // Back out on ThreadFactory failure or if                // shut down before lock acquired.                int c = ctl.get();                int rs = runStateOf(c);                if (rs < SHUTDOWN ||                    (rs == SHUTDOWN && firstTask == null)) {                    if (t.isAlive()) // precheck that t is startable                        throw new IllegalThreadStateException();                    /*worker-cnt应该就是workers的size,thread-pool中有多少工作线程,workers中就有                    多少个Worker对象*/                    workers.add(w);                       int s = workers.size();                    if (s > largestPoolSize)                        largestPoolSize = s;                    workerAdded = true;                }            } finally {                mainLock.unlock();            }            if (workerAdded) {                t.start();  /*启动上述封装了Worker对象的Thread对象的线程,将调用Worker的run()方法*/                workerStarted = true;            }        }    } finally {        if (! workerStarted)            addWorkerFailed(w);    }    return workerStarted;}

【Worker的run方法】
【Worker保存用户指定的Runnable对象为firstTask】
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this); /Worker将自己封装到Thread对象中/
}

【Worker的run调用runWorker】
public void run() {
runWorker(this);
}
【Worker最终执行用户指定的Runnable对象】
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask; /取出用户指定的Runable对象/
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(); /用户指定的Runable对象得到执行/
} 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);
}
}

0 0
原创粉丝点击