ThreadPoolExecutor 源码解读

ThreadPoolExecutor 是最普通的 ExecutorService 的实现。

参数最全的构造函数如下:

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
。。省略参数检查
        this.corePoolSize = corePoolSize;   //核心池大小
        this.maximumPoolSize = maximumPoolSize;   // 最大池大小
        this.workQueue = workQueue;               //任务队列
        this.keepAliveTime = unit.toNanos(keepAliveTime);  //线程无任务时的存活时间
        this.threadFactory = threadFactory;                //线程的构造工厂
        this.handler = handler;                    //RejectedExecutionHandler,任务队列满时的处理方式
    }

还有几个很重要的成员变量是:

    private final ReentrantLock mainLock = new ReentrantLock();  //访问线程池时,内部状态的锁
    //Set containing all worker threads in pool. Accessed only when
    //holding mainLock.   所有的worker,每个持有一个线程,并继承自AbstractQueuedSynchronizer
    private final HashSet<Worker> workers = new HashSet<Worker>();
    //终止时候的等待条件。
    private final Condition termination = mainLock.newCondition();

下面看看worker类,是一个私有内部类:

private final class Worker extends AbstractQueuedSynchronizer implements Runnable //实现了Runnable 
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) { //这个getTask方法就是检查了状态,并且从ThreadPoolExecutor的workQueue中,拿到一个Runnable的任务。 
            //这个方法还有另外的作用,就是如果当前池大于core则,清理当前线程。如果小于等于,则保持。
                w.lock();   //这个lock很重要,说明了这个线程当前是工作的,所以不会被interruptIdleWorkers中断,因为interruptIdleWorkers调用了worker的tryLock方法,判断是否是idle线程。
                //shutdownNow方法则调用interruptWorkers,中断所有worker.
                // 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);
        }
    }
    
private void processWorkerExit(Worker w, boolean completedAbruptly) {
        if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
            decrementWorkerCount();      // 如果是意外终止,减少线程池worker数目

        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            completedTaskCount += w.completedTasks;
            workers.remove(w);                  //移除当前的worker
        } finally {
            mainLock.unlock();
        }

        tryTerminate();

        int c = ctl.get();
        if (runStateLessThan(c, STOP)) {
            if (!completedAbruptly) {                    
                int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
                if (min == 0 && ! workQueue.isEmpty())
                    min = 1;
                if (workerCountOf(c) >= min)
                    return; // replacement not needed
            }
            addWorker(null, false);            //如果是非正常 或则在任务队列不为空的情况下,workerCountOf(c) < min  则。。,重新启动一个worker。
        }
    }

下面看看ThreadPoolExecutor 的execute方法:

submit方法,就是实例化了一个FutureTask对象返回,然后调用execute方法执行这个FutureTask。

    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }


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) {   //如果小于核心池,新建一个worker
            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))   //如果满了,就是addWorker(command, false)表示加入非核心
            reject(command);                   //如果addWorker失败了,就执行rejectHandle策略.
    }
    
 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))  //如果应该add,添加工作线程数目,退出循环,
                    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;
            w = new Worker(firstTask);
            final Thread t = w.thread;
            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 ||    //检查线程池没有关闭,或则关闭了firstTask为null
                        (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;
    }

最后看看Shutdown和ShutdowNow, 这两个方法:

    public void shutdown() {   
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();   //检查是否有这个权限
            advanceRunState(SHUTDOWN);    //设置状态为SHUTDOWN
            interruptIdleWorkers();  //给idle的work发送中断
            onShutdown(); // hook for ScheduledThreadPoolExecutor  关闭钩子调用
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
    }
    
    public List<Runnable> shutdownNow() {
        List<Runnable> tasks;
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();
            advanceRunState(STOP);    //设置状态为STOP
            interruptWorkers();   //给所有线程发送中断,正在工作的线程也会收到这个中断。
            tasks = drainQueue();
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
        return tasks;
    }

之后看看这篇博客,写的很好。

http://my.oschina.net/xionghui/blog/494698


你可能感兴趣的:(ThreadPoolExecutor 源码解读)