线程池ThreadPoolExecutor源码

目录

1. 创建线程池

2. executor方法:

addWorker(Runnable firstTask, boolean core)

getTask() : 获取对列中的任务

runWorker(Worker w) : 执行任务

processWorkerExit(Worker w, boolean completedAbruptly)

addWorkerFailed(Worker w)

shutdown()

shutdownNow()

isShutdown()

getTaskCount()


1. 创建线程池

ExecutorService pool = new ThreadPoolExecutor(
                                            3,
                                            5,
                                            8,
                                            TimeUnit.SECONDS,
                                            new ArrayBlockingQueue<>(5),
                                            Executors.defaultThreadFactory(),
                                            new ThreadPoolExecutor.AbortPolicy()
                                        );
pool.execute(new Runnable() {
     @Override
     public void run() {
         System.out.println("!!!!!!!!!!!!!!!!!!");
     }
});

2. executor方法:

private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
public void execute(Runnable command) {
    //如果没有任务,直接抛空指针异常
    if (command == null)
        throw new NullPointerException();
        
    //获取线程池的状态码
    int c = ctl.get();
    //如果工作线程的任务数小于核心线程数
    if (workerCountOf(c) < corePoolSize) {

        //直接新增核心线程去执行任务
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }

    //线程状态是running, 将任务放入阻塞队列中
    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);
    }
    //如果线程的状态是:shutdown或stop, 拒绝新任务
    else if (!addWorker(command, false))
        reject(command);
}

addWorker(Runnable firstTask, boolean core)

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;
}

getTask() : 获取对列中的任务

private Runnable getTask() {
  boolean timedOut = false; // Did the last poll() time out?

  for (;;) {
      int c = ctl.get();
      int rs = runStateOf(c);

      // Check if queue empty only if necessary.
      if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
          decrementWorkerCount();
          return null;
      }

      //线程的个数
      int wc = workerCountOf(c);

      // Are workers subject to culling?
      boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

      if ((wc > maximumPoolSize || (timed && timedOut))
          && (wc > 1 || workQueue.isEmpty())) {
          //线程数减1
          if (compareAndDecrementWorkerCount(c))
              return null;
          continue;
      }

      try {
          Runnable r = timed ?
              //阻塞超时
              workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
              //
              workQueue.take();
          if (r != null)
              return r;
          timedOut = true;
      } catch (InterruptedException retry) {
          timedOut = false;
      }
  }
}

runWorker(Worker w) : 执行任务

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);
  }
}

  processWorkerExit(Worker w, boolean completedAbruptly)

private void processWorkerExit(Worker w, boolean completedAbruptly) {
  if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
      //线程数减1
      decrementWorkerCount();

  final ReentrantLock mainLock = this.mainLock;
  mainLock.lock();
  try {
      completedTaskCount += w.completedTasks;
      workers.remove(w);
  } finally {
      mainLock.unlock();
  }

  tryTerminate();

  int c = ctl.get();
  //线程状态是否小于Stop
  if (runStateLessThan(c, STOP)) {
      if (!completedAbruptly) {
          int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
          //当前线程池中线程的个数最少保留一个(核心线程设置超时)
          if (min == 0 && ! workQueue.isEmpty())
              min = 1;
          //当前线程池中线程的个数是否大于等于核心线程数
          if (workerCountOf(c) >= min)
              //设置核心线程超时?线程池中保留1个线程 :线程池中保留corePoolSize
              return; // replacement not needed
      }
      //新增一个线程, 从队列中拿任务
      addWorker(null, false);
  }
}

addWorkerFailed(Worker w)

private void addWorkerFailed(Worker w) {
  final ReentrantLock mainLock = this.mainLock;
  mainLock.lock();
  try {
      if (w != null)
          workers.remove(w);
      decrementWorkerCount();
      tryTerminate();
  } finally {
      mainLock.unlock();
  }
}

shutdown()

public void shutdown() {
  final ReentrantLock mainLock = this.mainLock;
  mainLock.lock();
  try {
      checkShutdownAccess();
      advanceRunState(SHUTDOWN);
      interruptIdleWorkers();
      onShutdown(); // hook for ScheduledThreadPoolExecutor
  } finally {
      mainLock.unlock();
  }
  tryTerminate();
}

shutdownNow()

public List<Runnable> shutdownNow() {
  List<Runnable> tasks;
  final ReentrantLock mainLock = this.mainLock;
  mainLock.lock();
  try {
      checkShutdownAccess();
      advanceRunState(STOP);
      interruptWorkers();
      tasks = drainQueue();
  } finally {
      mainLock.unlock();
  }
  tryTerminate();
  return tasks;
}

isShutdown()

public boolean isShutdown() {
    return ! isRunning(ctl.get());
}

getTaskCount()

public long getTaskCount() {
  final ReentrantLock mainLock = this.mainLock;
  mainLock.lock();
  try {
      long n = completedTaskCount;
      for (Worker w : workers) {
          n += w.completedTasks;
          if (w.isLocked())
              ++n;
      }
      return n + workQueue.size();
  } finally {
      mainLock.unlock();
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

time Friend

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值