Executors

作者: 萍水相逢_程序员 | 来源:发表于2018-10-20 15:33 被阅读0次

    Executors生成常用的几种线程池执行者

    1. 可缓存线程池
      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);
        }
    
    
    1. 定长的线程池
       public static ExecutorService newFixedThreadPool(int nThreads) {
            return new ThreadPoolExecutor(nThreads, nThreads,
                                          0L, TimeUnit.MILLISECONDS,
                                          new LinkedBlockingQueue<Runnable>());
        }
    
       public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
            return new ThreadPoolExecutor(nThreads, nThreads,
                                          0L, TimeUnit.MILLISECONDS,
                                          new LinkedBlockingQueue<Runnable>(),
                                          threadFactory);
        }
    
    1. 定时线程池
        public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
            return new ScheduledThreadPoolExecutor(corePoolSize);
        }
    
        public static ScheduledExecutorService newScheduledThreadPool(
                int corePoolSize, ThreadFactory threadFactory) {
            return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
        }
    
    

    ScheduledThreadPoolExecutor是ThreadPoolExecutor的子类。最后还是调用ThreadPoolExecutor

        public ScheduledThreadPoolExecutor(int corePoolSize) {
            super(corePoolSize, Integer.MAX_VALUE,
                  DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
                  new DelayedWorkQueue());
        }
    
        public ScheduledThreadPoolExecutor(int corePoolSize,
                                           ThreadFactory threadFactory) {
            super(corePoolSize, Integer.MAX_VALUE,
                  DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
                  new DelayedWorkQueue(), threadFactory);
        }
    
    1. 单列线程池
        public static ExecutorService newSingleThreadExecutor() {
            return new FinalizableDelegatedExecutorService
                (new ThreadPoolExecutor(1, 1,
                                        0L, TimeUnit.MILLISECONDS,
                                        new LinkedBlockingQueue<Runnable>()));
        }
    
        public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
            return new FinalizableDelegatedExecutorService
                (new ThreadPoolExecutor(1, 1,
                                        0L, TimeUnit.MILLISECONDS,
                                        new LinkedBlockingQueue<Runnable>(),
                                        threadFactory));
        }
    
    

    ThreadPoolExecutor参数的解释

        /**
         *corePoolSize 核心线程数 实际运行的线程数
         *maximumPoolSize 最多可创建的线程
         *keepAliveTime 非核心线程闲置线程最大存活时间
         *TimeUnit  keepAliveTime 的时间单位
         *threadFactory 线程工厂,好处就是允许应用程序使用特殊的线程子类,设置属性等等
         *RejectedExecutionHandler   在方法execute()中提交的新任务将被拒绝后处理方式
         * Creates a new {@code ThreadPoolExecutor} with the given initial
         * parameters.
         *
         * @param corePoolSize the number of threads to keep in the pool, even
         *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
         * @param maximumPoolSize the maximum number of threads to allow in the
         *        pool
         * @param keepAliveTime when the number of threads is greater than
         *        the core, this is the maximum time that excess idle threads
         *        will wait for new tasks before terminating.
         * @param unit the time unit for the {@code keepAliveTime} argument
         * @param workQueue the queue to use for holding tasks before they are
         *        executed.  This queue will hold only the {@code Runnable}
         *        tasks submitted by the {@code execute} method.
         * @param threadFactory the factory to use when the executor
         *        creates a new thread
         * @param handler the handler to use when execution is blocked
         *        because the thread bounds and queue capacities are reached
         * @throws IllegalArgumentException if one of the following holds:<br>
         *         {@code corePoolSize < 0}<br>
         *         {@code keepAliveTime < 0}<br>
         *         {@code maximumPoolSize <= 0}<br>
         *         {@code maximumPoolSize < corePoolSize}
         * @throws NullPointerException if {@code workQueue}
         *         or {@code threadFactory} or {@code handler} is null
         */
        public ThreadPoolExecutor(int corePoolSize,
                                  int maximumPoolSize,
                                  long keepAliveTime,
                                  TimeUnit unit,
                                  BlockingQueue<Runnable> workQueue,
                                  ThreadFactory threadFactory,
                                  RejectedExecutionHandler handler) {
            if (corePoolSize < 0 ||
                maximumPoolSize <= 0 ||
                maximumPoolSize < corePoolSize ||
                keepAliveTime < 0)
                throw new IllegalArgumentException();
            if (workQueue == null || threadFactory == null || handler == null)
                throw new NullPointerException();
            this.corePoolSize = corePoolSize;
            this.maximumPoolSize = maximumPoolSize;
            this.workQueue = workQueue;
            this.keepAliveTime = unit.toNanos(keepAliveTime);
            this.threadFactory = threadFactory;
            this.handler = handler;
        }
    
    

    举例使用:
    Fresco线程池使用情况

    //ThreadFactory 的用法
    public class PriorityThreadFactory implements ThreadFactory {
    
      private final int mThreadPriority;
    
      /**
       * Creates a new PriorityThreadFactory with a given priority.
       *
       * <p>This value should be set to a value compatible with
       * {@link android.os.Process#setThreadPriority}, not {@link Thread#setPriority}.
       *
       */
      public PriorityThreadFactory(int threadPriority) {
        mThreadPriority = threadPriority;
      }
    
      @Override
      public Thread newThread(final Runnable runnable) {
        Runnable wrapperRunnable = new Runnable() {
          @Override
          public void run() {
            try {
              Process.setThreadPriority(mThreadPriority);
            } catch (Throwable t) {
              // just to be safe
            }
            runnable.run();
          }
        };
        return new Thread(wrapperRunnable);
      }
    
    }
    
    

    在android 核心线程数值设置一般通过如下方式获取

      public static final int DEFAULT_MAX_NUM_THREADS = Runtime.getRuntime().availableProcessors();
    
    public class DefaultExecutorSupplier implements ExecutorSupplier {
      // Allows for simultaneous reads and writes.
      private static final int NUM_IO_BOUND_THREADS = 2;
      private static final int NUM_LIGHTWEIGHT_BACKGROUND_THREADS = 1;
    
      private final Executor mIoBoundExecutor;
      private final Executor mDecodeExecutor;
      private final Executor mBackgroundExecutor;
      private final Executor mLightWeightBackgroundExecutor;
    
      public DefaultExecutorSupplier(int numCpuBoundThreads) {
        ThreadFactory backgroundPriorityThreadFactory =
            new PriorityThreadFactory(Process.THREAD_PRIORITY_BACKGROUND);
    
        mIoBoundExecutor = Executors.newFixedThreadPool(NUM_IO_BOUND_THREADS);
        mDecodeExecutor = Executors.newFixedThreadPool(
            numCpuBoundThreads,
            backgroundPriorityThreadFactory);
        mBackgroundExecutor = Executors.newFixedThreadPool(
            numCpuBoundThreads,
            backgroundPriorityThreadFactory);
        mLightWeightBackgroundExecutor = Executors.newFixedThreadPool(
            NUM_LIGHTWEIGHT_BACKGROUND_THREADS,
            backgroundPriorityThreadFactory);
    
      }
    
      @Override
      public Executor forLocalStorageRead() {
        return mIoBoundExecutor;
      }
    
      @Override
      public Executor forLocalStorageWrite() {
        return mIoBoundExecutor;
      }
    
      @Override
      public Executor forDecode() {
        return mDecodeExecutor;
      }
    
      @Override
      public Executor forBackgroundTasks() {
        return mBackgroundExecutor;
      }
    
      @Override
      public Executor forLightweightBackgroundTasks() {
        return mLightWeightBackgroundExecutor;
      }
    }
    
    

    看下bolts给android设置参数 构造Executor

    /**
     * This was created because the helper methods in {@link java.util.concurrent.Executors} do not work
     * as people would normally expect.
     *
     * Normally, you would think that a cached thread pool would create new threads when necessary,
     * queue them when the pool is full, and kill threads when they've been inactive for a certain
     * period of time. This is not how {@link java.util.concurrent.Executors#newCachedThreadPool()}
     * works.
     *
     * Instead, {@link java.util.concurrent.Executors#newCachedThreadPool()} executes all tasks on
     * a new or cached thread immediately because corePoolSize is 0, SynchronousQueue is a queue with
     * size 0 and maxPoolSize is Integer.MAX_VALUE. This is dangerous because it can create an unchecked
     * amount of threads.
     */
    /* package */ final class AndroidExecutors {
    
      private static final AndroidExecutors INSTANCE = new AndroidExecutors();
    
      private final Executor uiThread;
    
      private AndroidExecutors() {
        uiThread = new UIThreadExecutor();
      }
    
      /**
       * Nexus 5: Quad-Core
       * Moto X: Dual-Core
       *
       * AsyncTask:
       *   CORE_POOL_SIZE = CPU_COUNT + 1
       *   MAX_POOL_SIZE = CPU_COUNT * 2 + 1
       *
       * https://github.com/android/platform_frameworks_base/commit/719c44e03b97e850a46136ba336d729f5fbd1f47
       */
      private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
      /* package */ static final int CORE_POOL_SIZE = CPU_COUNT + 1;
      /* package */ static final int MAX_POOL_SIZE = CPU_COUNT * 2 + 1;
      /* package */ static final long KEEP_ALIVE_TIME = 1L;
    
      /**
       * Creates a proper Cached Thread Pool. Tasks will reuse cached threads if available
       * or create new threads until the core pool is full. tasks will then be queued. If an
       * task cannot be queued, a new thread will be created unless this would exceed max pool
       * size, then the task will be rejected. Threads will time out after 1 second.
       *
       * Core thread timeout is only available on android-9+.
       *
       * @return the newly created thread pool
       */
      public static ExecutorService newCachedThreadPool() {
        ThreadPoolExecutor executor =  new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            KEEP_ALIVE_TIME, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());
    
        allowCoreThreadTimeout(executor, true);
    
        return executor;
      }
    
      /**
       * Creates a proper Cached Thread Pool. Tasks will reuse cached threads if available
       * or create new threads until the core pool is full. tasks will then be queued. If an
       * task cannot be queued, a new thread will be created unless this would exceed max pool
       * size, then the task will be rejected. Threads will time out after 1 second.
       *
       * Core thread timeout is only available on android-9+.
       *
       * @param threadFactory the factory to use when creating new threads
       * @return the newly created thread pool
       */
      public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        ThreadPoolExecutor executor =  new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(),
                threadFactory);
    
        allowCoreThreadTimeout(executor, true);
    
        return executor;
      }
    
      /**
       * Compatibility helper function for
       * {@link java.util.concurrent.ThreadPoolExecutor#allowCoreThreadTimeOut(boolean)}
       *
       * Only available on android-9+.
       *
       * @param executor the {@link java.util.concurrent.ThreadPoolExecutor}
       * @param value true if should time out, else false
       */
      @SuppressLint("NewApi")
      public static void allowCoreThreadTimeout(ThreadPoolExecutor executor, boolean value) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
          //允许核心线程超时
          executor.allowCoreThreadTimeOut(value);
        }
      }
    
      /**
       * An {@link java.util.concurrent.Executor} that executes tasks on the UI thread.
       */
      public static Executor uiThread() {
        return INSTANCE.uiThread;
      }
    
      /**
       * An {@link java.util.concurrent.Executor} that runs tasks on the UI thread.
       */
      private static class UIThreadExecutor implements Executor {
        @Override
        public void execute(Runnable command) {
          new Handler(Looper.getMainLooper()).post(command);
        }
      }
    }
    
    

    说明 newCachedThreadPool 通过设置核心线程数为0,来达到空闲线程的回收。

    如果有设置核心线程的数量,并且没有设置ThreadPoolExecutor中属性allowCoreThreadTimeOut为true,则核心线程不会销毁。

    总结 设置allowCoreThreadTimeOut为true,在选择线程池的时候,可以newFixedThreadPool来代替newCachedThreadPool

    ThreadPoolExecutor执行顺序

    1. 当线程数小于核心线程数时,创建线程。
    2. 当线程数大于等于核心线程数,且任务队列未满时,将任务放入任务队列。
    3. 当线程数大于等于核心线程数,且任务队列已满
      3.1. 若线程数小于最大线程数,创建线程
      3.2. 若线程数等于最大线程数,抛出异常,拒绝任务

    相关文章

      网友评论

          本文标题:Executors

          本文链接:https://www.haomeiwen.com/subject/vicmzftx.html