多线程进阶JUC之线程池ThreadPoolExecutor

线程池

记忆场景图
在这里插入图片描述

三大方法创建线程池(不用)

阿里巴巴开发手册 不允许使用Executors去创建线程池。因为,FixedThreadPool和SingleThreadPool允许的请求队列长度为Interger.Max_Value,可能导致oom。CacheThreadPool和ScheduledThreadPool允许创建的线程数量为Interger.Max_Value,可能导致oom。

故必须使用ThreadPoolExecutor创建线程池

  1. // ExecutorService executorService = Executors.newSingleThreadExecutor();// 单个线程java.util.concurrent.Executors$FinalizableDelegatedExecutorService
 public static ExecutorService newSingleThreadExecutor() {
    
    
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}
  1. // ExecutorService executorService = Executors.newFixedThreadPool(5);// 创建固定线程池大小java.util.concurrent.ThreadPoolExecutor
public static ExecutorService newFixedThreadPool(int nThreads) {
    
    
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}
  1. // ExecutorService executorService = Executors.newCachedThreadPool();// 可伸缩的线程池,遇强则强。
public static ExecutorService newCachedThreadPool() {
    
    
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

七大参数(自定义ThreadPoolExecutor指定)

public ThreadPoolExecutor(int corePoolSize, 				 // 1.核心线程池大小
                          int maximumPoolSize, 				 // 2.最大核心线程池大小
                          long keepAliveTime, 				 // 3.超时了无人调用就释放
                          TimeUnit unit, 					 // 4.超时单位
                          BlockingQueue<Runnable> workQueue, //5. 阻塞队列
                          ThreadFactory threadFactory, 		 // 6.创建线程的工厂
                          RejectedExecutionHandler handler) {
    
    // 7.拒绝策略
    if (corePoolSize < 0 ||
        maximumPoolSize <= 0 ||
        maximumPoolSize < corePoolSize ||
        keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();
    this.acc = System.getSecurityManager() == null ?
            null :
            AccessController.getContext();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

调优!CPU密集型&IO密集型

调优。最大线程池如何定义?maximumPoolSize

  1. CPU密集型 12核CPU同时运行,保证cpu效率最高
// CPU密集型。防止运维打死我,获取此电脑的cpu处理器核数
int cpuProcessor = Runtime.getRuntime().availableProcessors();
  1. IO密集型 > 判断程序中十分耗io的线程。15个大型任务,io十分占用资源。定义多余15个线程。

四种拒绝策略(自定义ThreadPoolExecutor指定)

  1. new ThreadPoolExecutor.AbortPolicy() ); // 流产堕胎拒绝策略,>2+5个线程后抛异常报RejectedExecutionException错
  2. // new ThreadPoolExecutor.CallerRunsPolicy() ); // 哪来的滚自己公司办卡,打来电话滚跑策略。main线程去打发执行
  3. // new ThreadPoolExecutor.DiscardPolicy() ); // 队列满不抛异常,一走了之抛弃策略
  4. // new ThreadPoolExecutor.DiscardOldestPolicy() ); // 队列满不抛异常,尝试和最早执行的线程竞争,不当备胎,努力尝试后不行一走了之抛弃策略、
/**
 * 三大方法
 * 七大参数
 * 四种拒绝策略
 * @Author Weton Li
 * @Date 2021/2/11 09:09
 */
public class MyThreadPoolExecutor {
    
    
    public static void main(String[] args) {
    
    
//        ExecutorService executorService = Executors.newSingleThreadExecutor();// 单个线程java.util.concurrent.Executors$FinalizableDelegatedExecutorService

//        ExecutorService executorService = Executors.newFixedThreadPool(5);// 创建固定线程池大小java.util.concurrent.ThreadPoolExecutor

//        ExecutorService executorService = Executors.newCachedThreadPool();// 可伸缩的线程池,遇强则强。

        // CPU密集型。防止运维打死我,获取此电脑的cpu处理器核数
        int cpuProcessor = Runtime.getRuntime().availableProcessors();
        /*自定义线程池,工作只使用此方法*/
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,4,3, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy() ); // 流产堕胎拒绝策略,>2+5个线程后抛异常报RejectedExecutionException错
//                new ThreadPoolExecutor.CallerRunsPolicy() ); // 哪来的滚自己公司办卡,打来电话滚跑策略。main线程去打发执行
//                new ThreadPoolExecutor.DiscardPolicy() ); // 队列满不抛异常,一走了之抛弃策略
//                new ThreadPoolExecutor.DiscardOldestPolicy() ); // 队列满不抛异常,尝试和最早执行的线程竞争,不当备胎,努力尝试后不行一走了之抛弃策略、

        try {
    
    
            for (int i = 0; i < 8; i++) {
    
    
    //            new Thread().start();
//                executorService.execute(()->{ // 使用线程池创建线程
                threadPoolExecutor.execute(()->{
    
    
                    System.out.println(Thread.currentThread().getName()+"执行ok");
                });
            }
//            System.out.println(executorService.getClass());
            System.out.println(threadPoolExecutor.getClass());
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            // 关闭线程池
//            executorService.shutdown();
            threadPoolExecutor.shutdown();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_47119598/article/details/113789216