浅皮懔 发表于 2025-6-2 00:18:09

为什么说不推荐使用Executors创建线程池

首先通过executors创建的线程只有以下五种
Executors.newCachedThreadPool();

通过构造方法可以得知
无参构造

           /**
         * 最大线程数是 Integer的最大值
         * 等待队列使用的是SynchronousQueue
         *SynchronousQueue 没有容量,等待消费者 transfer
         */
    public static ExecutorService newCachedThreadPool() {
      return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                    60L, TimeUnit.SECONDS,
                                    new SynchronousQueue<Runnable>());
    }有参构造

          /**
           * 通过参数传入线程工厂
           */
   public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
      return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                    60L, TimeUnit.SECONDS,
                                    new SynchronousQueue<Runnable>(),
                                    threadFactory);
    }Executors.newScheduledThreadPool(5);

        /**
         * 核心线程数可以通过入参控制
         * 最大线程数是 Integer的最大值
         * 等待队列使用的是DelayedWork
         *DelayedWork 数据结果使用的是可以动态扩容的数组
         */
    public ScheduledThreadPoolExecutor(int corePoolSize) {
      super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
            new DelayedWorkQueue());
    }Executors.newSingleThreadExecutor();

        /**
         * 核心线程和最大线程数都是1,只有单个线程的线程池
         * 等待队列使用的是LinkedBlockingQueue
         *LinkedBlockingQueue 数据结构使用的是单向链表,同时等待队列的大小是 Integer的上限
         */
   public static ExecutorService newSingleThreadExecutor() {
      return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }Executors.newWorkStealingPool();

无参构造

      /**
         * 核心线程数使用的是jvm中可用的处理器数量
         */
    public static ExecutorService newWorkStealingPool() {
      return new ForkJoinPool
            (Runtime.getRuntime().availableProcessors(),
             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
             null, true);
    }有参构造

      /**
         * 核心线程数是参数大小
         */
    public static ExecutorService newWorkStealingPool(int parallelism) {
      return new ForkJoinPool
            (parallelism,
             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
             null, true);
    }Executors.newFixedThreadPool(10);

        /**
         * 核心线程数和最大线程数是一样的,通过入参配置
         * LinkedBlockingQueue 数据结构使用的是单向链表,同时等待队列的大小是 Integer的上限
         */
   public static ExecutorService newFixedThreadPool(int nThreads) {
      return new ThreadPoolExecutor(nThreads, nThreads,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>());
    }通过Executors创建的线程池通常并不满足我们日常开发的使用场景

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 为什么说不推荐使用Executors创建线程池