ExecutorService源码分析

来源:互联网 发布:c语言取反符号 编辑:程序博客网 时间:2024/06/15 19:03

看了几次,今天看到同事写的类似于这个executorService的模式的例子,又看了下,简单记录下

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) {            if (addWorker(command, true))                return;            c = ctl.get();        }        //线程都在运行&&此时没有线程再来管任务,任务只好进入workQueue        if (isRunning(c) && workQueue.offer(command)) {        //进入队列的这段时间,再次确认下是不是所有的线程都在运行                    int recheck = ctl.get();            // !isRunning(recheck) 线程池没有运行 && 移除刚刚加入的任务            if (! isRunning(recheck) && remove(command))            //执行拒绝策略                reject(command);            //工作的线程数为0            else if (workerCountOf(recheck) == 0)           //null,false 只是启动一个线程                addWorker(null, false);        }                else if (!addWorker(command, false))            reject(command);    }     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;                   //cas成功,表示ctl计数worker的个数+1,退出该循环,往下执行                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());/* private static final int RUNNING    = -1 ;    private static final int SHUTDOWN   =  0 ;    private static final int STOP       =  1 ;    private static final int TIDYING    =  2 ;    private static final int TERMINATED =  3 ;*/                    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) {                //启动线程,workerStarted is true                    t.start();                    workerStarted = true;                }            }        } finally {            if (! workerStarted)                addWorkerFailed(w);        }        return workerStarted; }