Executors

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. 若线程数等于最大线程数,抛出异常,拒绝任务
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342