• 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. }

  • 相关阅读:
    赛宁网安携车联网、工控安全强势亮相网络安全宣传周
    ES6 class类的静态方法static有什么用
    ps安装遇到问题
    模块化设计瞎谈
    Docker系列--在容器中安装JDK的方法(有示例)
    原生JavaScript实现本地存储(localStorage)和会话存储(sessionStorage)
    数据结构中的堆(Java)
    数据结构之单链表
    Linux系统IO
    【突然想多了解一点】可以用 Task.Run() 将同步方法包装为异步方法吗?
  • 原文地址:https://blog.csdn.net/sai739295732/article/details/127654261