并发编程 六 Executor线程池


    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. 
         * 
     1.如果工作线程小于核心线程池数量,尝试新建一个工作线程执行任务addWorker。 
         addWorker将会自动检查线程池状态和工作线程数,以防在添加工作线程的过程中, 
     线程池被关闭。 
         * 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. 
         * 
     2.如果创建工作线程执行任务失败,则任务入队列,如果入队列成功, 
     我们仍需要二次检查线程池状态,以防在入队列的过程中,线程池关闭。 
     如果线程池关闭,则回滚任务。 
         * 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();  
        }  
    //如果当前工作线程数大于核心线程池数量,检查运行状态,如果是正在运行,则添加任务到任务队列  
        if (isRunning(c) && workQueue.offer(command)) {  
            int recheck = ctl.get();  
        //重新检查线程池运行状态,如果线程池非处于运行状态,则移除任务  
            if (! isRunning(recheck) && remove(command))  
                reject(command);//移除成功,则进行拒绝任务处理  
            else if (workerCountOf(recheck) == 0)  
            //如线程池已关闭,且工作线程为0,则创建一个空闲工作线程  
                addWorker(null, false);  
        }  
       //根据最大线程池数量,判断是否应该添加工作线程,如果当前工作线程数量小于最大线程池数量,则尝试添加  
       //工作线程线程执行任务,如果尝试失败,则拒绝任务处理  
        else if (!addWorker(command, false))  
            reject(command);  
    } 
/** 
    
    根据当前线程池状态和核心线程池数量与最大线程池数量,检查是否应该, 
    添加工作线程执行任务。如果应该添加工作线程,则更新工作线程数, 
    如果调整成功,则创建工作线程,执行任务。如果线程是已关闭或正在关闭, 
    则添加工作线程失败。如果线程工厂创建线程失败,则返回false,如果由于 
    线程工厂返回null或OutOfMemoryError等原因,执行回滚清除工作。 

    */  
   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()))  
    //如果线程池已关闭或线程池正在关闭,提交的任务为null且任务队列不为空,则直接返回false  
    //添加工作线程失败。  
               return false;  
  
           for (;;) {  
               int wc = workerCountOf(c);  
               if (wc >= CAPACITY ||  
                   wc >= (core ? corePoolSize : maximumPoolSize))  
        //如果工作线程数量大于线程池容量,  
        //或当前工作线程数量大于core(如果core,为true,则为corePoolSize,否则maximumPoolSize)  
                   return false;  
               if (compareAndIncrementWorkerCount(c))  
        //CAS操作工作线程数,即原子操作工作线程数+1,成功则跳出自旋  
                   break retry;  
               c = ctl.get();  // Re-read ctl  
               if (runStateOf(c) != rs)  
        //如果在判断是否应该添加工作线程执行任务和CAS操作工作线程数,  
        //线程状态改变,跳出本次自旋  
                   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 ||  
                       (rs == SHUTDOWN && firstTask == null)) {  
        //如果线程池是正在运行或线程池正在关闭,任务为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;  
   } 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值