当前位置:   article > 正文

ThreadPoolExecutor-线程池如何保证线程不被销毁_executors.newfixedthreadpool线程执行完自动释放吗

executors.newfixedthreadpool线程执行完自动释放吗

目录

前言

线程池使用入口

源码

结论


前言

1、通常情况下 我们new一个线程执行任务,任务执行完之后线程也随之销毁了

2、为了减少创建线程的开销,使线程可以复用,我们使用线程池

3、那么问题来了,线程池是如何保证池子里的线程执行完不被销毁的呢?

线程池使用入口

入口:我们使用线程池时,代码如下

Executors.newFixedThreadPool(5);
  1. public static ExecutorService newFixedThreadPool(int nThreads) {
  2. return new ThreadPoolExecutor(nThreads, nThreads,
  3. 0L, TimeUnit.MILLISECONDS,
  4. new LinkedBlockingQueue<Runnable>());
  5. }

或者

  1. ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,10,60L,TimeUnit.SECONDS,new LinkedBlockingDeque<Runnable>());
  2. threadPoolExecutor.execute(new Runnable() {
  3. @Override
  4. public void run() {
  5. //business code..
  6. }
  7. });

源码

所以我们从execute这个方法开始探寻

  1. public void execute(Runnable command) {
  2. if (command == null)
  3. throw new NullPointerException();
  4. /*
  5. * Proceed in 3 steps:
  6. *
  7. * 1. If fewer than corePoolSize threads are running, try to
  8. * start a new thread with the given command as its first
  9. * task. The call to addWorker atomically checks runState and
  10. * workerCount, and so prevents false alarms that would add
  11. * threads when it shouldn't, by returning false.
  12. *
  13. * 2. If a task can be successfully queued, then we still need
  14. * to double-check whether we should have added a thread
  15. * (because existing ones died since last checking) or that
  16. * the pool shut down since entry into this method. So we
  17. * recheck state and if necessary roll back the enqueuing if
  18. * stopped, or start a new thread if there are none.
  19. *
  20. * 3. If we cannot queue task, then we try to add a new
  21. * thread. If it fails, we know we are shut down or saturated
  22. * and so reject the task.
  23. */
  24.   //clt保存了两种状态 当前线程数workerCountOf(c) 和 线程池的状态 runStateOf(c)
  25. int c = ctl.get();
  26.   //如果当前线程数 < 核心线程数 直接增加一个线程
  27. if (workerCountOf(c) < corePoolSize) {
  28. if (addWorker(command, true))
  29. return;
  30. c = ctl.get();
  31. }
  32.   //如果线程池状态是RUNNING 且 阻塞队列可以继续添加任务
  33. if (isRunning(c) && workQueue.offer(command)) {
  34. int recheck = ctl.get();
  35.   //如果线程池状态不是RUNNING 且 成功移除任务
  36. if (! isRunning(recheck) && remove(command))
  37.   //拒绝执行当前任务
  38. reject(command);
  39.   //当前线程数 == 0
  40. else if (workerCountOf(recheck) == 0)
  41. addWorker(null, false);
  42. }
  43.   //执行任务失败 - 拒绝执行
  44. else if (!addWorker(command, false))
  45. reject(command);
  46. }

发现重点在addWorker方法中:

  1. private boolean addWorker(Runnable firstTask, boolean core) {
  2. retry:
  3. for (;;) {
  4. int c = ctl.get();
  5.   //获取线程池的状态
  6. int rs = runStateOf(c);
  7. // Check if queue empty only if necessary.
  8.   //线程池状态异常 则退出不执行任务
  9. if (rs >= SHUTDOWN &&
  10. ! (rs == SHUTDOWN &&
  11. firstTask == null &&
  12. ! workQueue.isEmpty()))
  13. return false;
  14. //循环
  15. for (;;) {
  16.   //获取当前线程数
  17. int wc = workerCountOf(c);
  18.   //如果 当前线程数 大于 线程池最大线程容纳数量 或者 大于 设定的最大线程数 不执行任务
  19. if (wc >= CAPACITY ||
  20. wc >= (core ? corePoolSize : maximumPoolSize))
  21. return false;
  22.   //用CAS算法 将当前线程数加1,并跳出循环 继续执行
  23. if (compareAndIncrementWorkerCount(c))
  24. break retry;
  25. c = ctl.get(); // Re-read ctl
  26. if (runStateOf(c) != rs)
  27. continue retry;
  28. // else CAS failed due to workerCount change; retry inner loop
  29. }
  30. }
  31. boolean workerStarted = false;
  32. boolean workerAdded = false;
  33. Worker w = null;
  34. try {
  35.   //Worker是ThreadPoolExecutor的私有内部类,实现了Runnable接口
  36. w = new Worker(firstTask);
  37. final Thread t = w.thread;
  38. if (t != null) {
  39. final ReentrantLock mainLock = this.mainLock;
  40.   //加锁 防并发
  41. mainLock.lock();
  42. try {
  43. // Recheck while holding lock.
  44. // Back out on ThreadFactory failure or if
  45. // shut down before lock acquired.
  46.   //再次检查线程池状态
  47. int rs = runStateOf(ctl.get());
  48. //如果线程池状态正常 或者 是SHUTDOWN且任务是空的,继续执行
  49. if (rs < SHUTDOWN ||
  50. (rs == SHUTDOWN && firstTask == null)) {
  51.   //线程的alive是指线程已经开始执行并且没有销毁,所以如果是alive则抛异常
  52. if (t.isAlive()) // precheck that t is startable
  53. throw new IllegalThreadStateException();
  54. //workers是线程池定义的存放Worker的集合 HashSet<Worker> workers
  55. workers.add(w);
  56. int s = workers.size();
  57. if (s > largestPoolSize)
  58. largestPoolSize = s;
  59. workerAdded = true;
  60. }
  61. } finally {
  62. mainLock.unlock();
  63. }
  64.   //如果前边没问题 则开始执行线程run方法
  65. if (workerAdded) {
  66. t.start();
  67. workerStarted = true;
  68. }
  69. }
  70. } finally {
  71. if (! workerStarted)
  72. addWorkerFailed(w);
  73. }
  74. return workerStarted;
  75. }

接下来我们需要看一下Worker类和它的run方法

  1. Worker(Runnable firstTask) {
  2. setState(-1); // inhibit interrupts until runWorker
  3. this.firstTask = firstTask;
  4. this.thread = getThreadFactory().newThread(this);
  5. }

构造方法中 创建了一个线程

  1. public void run() {
  2. runWorker(this);
  3. }

然后进入runWorker方法

  1. final void runWorker(Worker w) {
  2. Thread wt = Thread.currentThread();
  3. Runnable task = w.firstTask;
  4. w.firstTask = null;
  5. w.unlock(); // allow interrupts
  6. boolean completedAbruptly = true;
  7. try {
  8.   //如果task不为空 或者 getTask不为空时 会一直循环
  9.   //有任务时肯定不为空,没任务时task=null,所以要维持while永真,getTask一定不为空
  10. while (task != null || (task = getTask()) != null) {
  11. w.lock();
  12. // If pool is stopping, ensure thread is interrupted;
  13. // if not, ensure thread is not interrupted. This
  14. // requires a recheck in second case to deal with
  15. // shutdownNow race while clearing interrupt
  16. if ((runStateAtLeast(ctl.get(), STOP) ||
  17. (Thread.interrupted() &&
  18. runStateAtLeast(ctl.get(), STOP))) &&
  19. !wt.isInterrupted())
  20. wt.interrupt();
  21. try {
  22. beforeExecute(wt, task);
  23. Throwable thrown = null;
  24. try {
  25. task.run();
  26. } catch (RuntimeException x) {
  27. thrown = x; throw x;
  28. } catch (Error x) {
  29. thrown = x; throw x;
  30. } catch (Throwable x) {
  31. thrown = x; throw new Error(x);
  32. } finally {
  33. afterExecute(task, thrown);
  34. }
  35. } finally {
  36.   //执行完后将task置为null 继续走getTask的逻辑
  37. task = null;
  38. w.completedTasks++;
  39. w.unlock();
  40. }
  41. }
  42. completedAbruptly = false;
  43. } finally {
  44. processWorkerExit(w, completedAbruptly);
  45. }
  46. }

getTask 代码如下:

  1. /**
  2. * Performs blocking or timed wait for a task, depending on
  3. * current configuration settings, or returns null if this worker
  4. * must exit because of any of:
  5. * 1. There are more than maximumPoolSize workers (due to
  6. * a call to setMaximumPoolSize).
  7. * 2. The pool is stopped.
  8. * 3. The pool is shutdown and the queue is empty.
  9. * 4. This worker timed out waiting for a task, and timed-out
  10. * workers are subject to termination (that is,
  11. * {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
  12. * both before and after the timed wait, and if the queue is
  13. * non-empty, this worker is not the last thread in the pool.
  14. *
  15. * @return task, or null if the worker must exit, in which case
  16. * workerCount is decremented
  17. */
  18. private Runnable getTask() {
  19. boolean timedOut = false; // Did the last poll() time out?
  20. for (;;) {
  21. int c = ctl.get();
  22. int rs = runStateOf(c);
  23. // Check if queue empty only if necessary.
  24.   //如果线程池状态为STOP/TIDYING/TERMINATED 或者 线程池状态为SHUTDOWN/STOP/TIDYING/TERMINATED且阻塞队列为空
  25.   //return null 不再维持线程
  26. if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
  27. decrementWorkerCount();
  28. return null;
  29. }
  30. int wc = workerCountOf(c);
  31. // Are workers subject to culling?
  32.   //允许核心线程超时销毁 或者 当前线程数大于核心线程数
  33. boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
  34. if ((wc > maximumPoolSize || (timed && timedOut))
  35. && (wc > 1 || workQueue.isEmpty())) {
  36. if (compareAndDecrementWorkerCount(c))
  37. return null;
  38. continue;
  39. }
  40. try {
  41.   //重点:poll会一直阻塞直到超过keepAliveTime或者获取到任务
  42.   //take 会一直阻塞直到获取到任务
  43. //在没有任务的时候 如果没有特别设置allowCoreThreadTimeOut,我们的核心线程会一直阻塞在这里
  44. Runnable r = timed ?
  45. workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
  46. workQueue.take();
  47. if (r != null)
  48. return r;
  49. timedOut = true;
  50. } catch (InterruptedException retry) {
  51. timedOut = false;
  52. }
  53. }
  54. }

真相大白~

结论

总结就是:如果队列中没有任务时,小于核心数的线程会一直阻塞在获取任务的方法,直到返回任务。(判断阻塞时并没有核心线程和非核心线程的概念)

而且执行完后 会继续循环执行getTask的逻辑

附take poll源码注释:

  1. /**
  2. * Retrieves and removes the head of this queue, waiting if necessary
  3. * until an element becomes available.
  4. *
  5. * @return the head of this queue
  6. * @throws InterruptedException if interrupted while waiting
  7. */
  8. E take() throws InterruptedException;
  9. /**
  10. * Retrieves and removes the head of this queue, waiting up to the
  11. * specified wait time if necessary for an element to become available.
  12. *
  13. * @param timeout how long to wait before giving up, in units of
  14. * {@code unit}
  15. * @param unit a {@code TimeUnit} determining how to interpret the
  16. * {@code timeout} parameter
  17. * @return the head of this queue, or {@code null} if the
  18. * specified waiting time elapses before an element is available
  19. * @throws InterruptedException if interrupted while waiting
  20. */
  21. E poll(long timeout, TimeUnit unit)
  22. throws InterruptedException;

LinkedBlockingQueue实现的take方法:

这里有一个小问题,这里的while可不可以用if代替呢?

正常来说,每次signal时,只会有一个线程被唤醒,用if好像也没有问题,但是,实际上存在虚假唤醒的问题,即队列没有元素但是线程被唤醒了,需要while保证准确性。

所以,不能

2021-02-07 新增线程池结构图

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/332890?site
推荐阅读
相关标签
  

闽ICP备14008679号