• 线程池(重点)


    1.线程池的三大方法

    1. package com.kuang.pool;
    2. import java.util.concurrent.ExecutorService;
    3. import java.util.concurrent.Executors;
    4. //Executors工具类 三大方法
    5. //使用线程池,创建线程
    6. public class Demo01 {
    7. public static void main(String[] args) {
    8. // ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程。
    9. //ExecutorService threadPool = Executors.newFixedThreadPool(5);// 创建一个固定的线程池的大小。阻塞队列无线大,创建线程固定
    10. ExecutorService threadPool = Executors.newCachedThreadPool();//创建一个可伸缩的,遇强则强,遇弱则弱。 创建线程无线大,阻塞队列就一个容量
    11. try {
    12. for (int i = 0; i < 100; i++) {
    13. threadPool.execute(()->{
    14. System.out.println(Thread.currentThread().getName()+" ok");
    15. });
    16. }
    17. } catch (Exception e) {
    18. e.printStackTrace();
    19. } finally {
    20. threadPool.shutdown();
    21. }
    22. }
    23. }

    2.源码分析

    2.1 newSingleThreadExecutor() 

    1. public static ExecutorService newSingleThreadExecutor() {
    2. return new FinalizableDelegatedExecutorService
    3. (new ThreadPoolExecutor(1, 1,
    4. 0L, TimeUnit.MILLISECONDS,
    5. new LinkedBlockingQueue()));
    6. }

    2.2 newFixedThreadPool(int nThreads)

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

    2.3 newCachedThreadPool()

    1. public static ExecutorService newCachedThreadPool() {
    2. return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
    3. 60L, TimeUnit.SECONDS,
    4. new SynchronousQueue());
    5. }
    本质是:new ThreadPoolExecutor

    源码分析

    1. public ThreadPoolExecutor(int corePoolSize,
    2. int maximumPoolSize,
    3. long keepAliveTime,
    4. TimeUnit unit,
    5. BlockingQueue workQueue,
    6. ThreadFactory threadFactory,
    7. RejectedExecutionHandler handler) {
    8. if (corePoolSize < 0 ||
    9. maximumPoolSize <= 0 ||
    10. maximumPoolSize < corePoolSize ||
    11. keepAliveTime < 0)
    12. throw new IllegalArgumentException();
    13. if (workQueue == null || threadFactory == null || handler == null)
    14. throw new NullPointerException();
    15. this.acc = System.getSecurityManager() == null ?
    16. null :
    17. AccessController.getContext();
    18. this.corePoolSize = corePoolSize;
    19. this.maximumPoolSize = maximumPoolSize;
    20. this.workQueue = workQueue;
    21. this.keepAliveTime = unit.toNanos(keepAliveTime);
    22. this.threadFactory = threadFactory;
    23. this.handler = handler;
    24. }
    1. public ThreadPoolExecutor(int corePoolSize,//核心线程池大小
    2. int maximumPoolSize,//最大核心线池大小
    3. long keepAliveTime,//超时了没有人调用就会释放
    4. TimeUnit unit,//超时单位
    5. BlockingQueue workQueue,//阻塞队列
    6. ThreadFactory threadFactory,//线程工厂,创建线程的,一般不用动
    7. RejectedExecutionHandler handler) {// 拒绝策略
     
    

     手动 创建一个线程池 

           new

    4种拒绝策略

    1. package com.kuang.pool;
    2. import java.security.AccessController;
    3. import java.util.concurrent.*;
    4. import static java.util.concurrent.Executors.newSingleThreadExecutor;
    5. //Executors工具类 三大方法
    6. //使用线程池,创建线程
    7. /**
    8. * 第一种拒绝策略 new ThreadPoolExecutor.AbortPolicy() 超出,则不去执行那个多的,而且会抛异常RejectedExecutionException
    9. * 第二种拒绝策略 new ThreadPoolExecutor.CallerRunsPolicy() 哪个线程的创建出的这个线程,就回到哪个线程去执行
    10. * 第三种拒绝策略 new ThreadPoolExecutor.DiscardPolicy() 队列满了 丢掉任务, 不去执行,也不抛异常
    11. * 第四种拒绝策略 new ThreadPoolExecutor.DiscardOldestPolicy() 队列满了,会抛弃任务队列中最旧的任务也就是最先加入队列的,再把这个新任务添加进去。也不会抛异常!!!
    12. *
    13. */
    14. public class Demo01 {
    15. public static void main(String[] args) {
    16. // ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程。
    17. //ExecutorService threadPool = Executors.newFixedThreadPool(5);// 创建一个固定的线程池的大小。阻塞队列无线大,创建线程固定
    18. // ExecutorService threadPool = Executors.newCachedThreadPool();//创建一个可伸缩的,遇强则强,遇弱则弱。 创建线程无线大,阻塞队列就一个容量
    19. ExecutorService threadPool = new ThreadPoolExecutor(2
    20. , 5,
    21. 3,
    22. TimeUnit.SECONDS,
    23. new LinkedBlockingQueue<>(3),
    24. Executors.defaultThreadFactory(),
    25. new ThreadPoolExecutor.DiscardOldestPolicy()//银行满了,还有人进来,不处理这个人的,抛出异常.
    26. );
    27. try {
    28. //最大承载: Deque+max =5+3=8
    29. //超过 RejectedExecutionException
    30. for (int i =1; i <=9; i++) {
    31. int finalI = i;
    32. threadPool.execute(()->{
    33. System.out.println(Thread.currentThread().getName()+" ok"+ finalI);
    34. });
    35. }
    36. } catch (Exception e) {
    37. e.printStackTrace();
    38. } finally {
    39. threadPool.shutdown();
    40. }
    41. }
    42. }

    3. 最大线程到底该如何定义(调优)

    1、CPU密集型  CPU的内核为几, 最大线程就定义为几,可以保持CPU的效率最高!

    代码获取CPU的核数 

    System.out.println("CPU核心为:"+Runtime.getRuntime().availableProcessors());

    2、IO密集型  判断 你程序中十分耗IO的线程  就把最大线程定义 >15   比如

    程序 15 个大型任务,io十分占用资源,就设置最大线程定义为30

  • 相关阅读:
    喜新厌旧?IT公司为什么宁愿花20k招人,也不愿涨薪留住老员工
    <string.h>字符操作函数的实现(strcpy、strcat、mem)
    高考志愿填报,如果你要选择计算机类专业?
    CSS图片响应悬停效果
    Makfile总结
    leetCode热题100——两数之和(python)
    【计算机毕业设计】微信小程序:MHK自学平台的设计与实现——后附源码
    Google guava之Multiset简介说明
    Django channel 使用说明 -- 以聊天室为例
    语音噪声---学习笔记
  • 原文地址:https://blog.csdn.net/qq_53374893/article/details/132945774