• java 线程池执行流程源码讲解


    1. threadPoolExecutor.execute(); //执行过程。
    2. public void execute(Runnable command) {
    3. if (command == null)
    4. throw new NullPointerException();
    5. *
    6. * Proceed in 3 steps:
    7. *
    8. * 1. If fewer than corePoolSize threads are running, try to
    9. * start a new thread with the given command as its first
    10. * task. The call to addWorker atomically checks runState and
    11. * workerCount, and so prevents false alarms that would add
    12. * threads when it shouldn't, by returning false.
    13. *
    14. * 2. If a task can be successfully queued, then we still need
    15. * to double-check whether we should have added a thread
    16. * (because existing ones died since last checking) or that
    17. * the pool shut down since entry into this method. So we
    18. * recheck state and if necessary roll back the enqueuing if
    19. * stopped, or start a new thread if there are none.
    20. *
    21. * 3. If we cannot queue task, then we try to add a new
    22. * thread. If it fails, we know we are shut down or saturated
    23. * and so reject the task.
    24. *
    25. //获取运行线程数
    26. int c = ctl.get();
    27. //workerCountOf(c)获取工作线程个数是否小于核心线程数
    28. if (workerCountOf(c) < corePoolSize) {
    29. //增加addWorker(command, true) 增加addWorker 第二个线程数是否核心
    30. if (addWorker(command, true))
    31. return;
    32. c = ctl.get();
    33. }
    34. //如果大于核心线程数,判断是否运行,队列放入command
    35. if (isRunning(c) && workQueue.offer(command)) {
    36. int recheck = ctl.get();
    37. 没有运行线程,且可以进行队列出队列,执行拒绝策略(因为上次检查后已有的死亡)
    38. if (!isRunning(recheck) && remove(command))
    39. reject(command);
    40. 如果工作
    41. else if (workerCountOf(recheck) == 0)
    42. addWorker(null, false);
    43. }
    44. //如果添加非核心线程失败,走拒绝策略
    45. else if (!addWorker(command, false))
    46. reject(command);
    47. }

  • 相关阅读:
    使用OpenTelemetry、Spring Cloud Sleuth、Kafka和Jaeger实现分布式跟踪
    【SpringCloud】负载均衡
    windows下redis的安装及其他注意事项
    php实战案例记录(21)sprintf函数
    Java-1122
    Linux基础
    【Linux学习】跨平台开发 Linux + VS2019 环境配置(Ubantu16.04)
    线性方程组(二)
    大数据基础设施搭建 - JDK
    未更改定时任务默认线程池大小导致的定时任务阻塞问题
  • 原文地址:https://blog.csdn.net/sai739295732/article/details/127654261