欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

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

来源: javaer 分享于  点击 34634 次 点评:256

为什么说不推荐使用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创建的线程池通常并不满足我们日常开发的使用场景

相关栏目:

用户点评