Android AsyncTask的限制

AsyncTask中包含了一个全局静态线程池,其配置如下(各版本的具体数值会有不同):

    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE = 1;

    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);
        public Thread newThread(Runnable r) {
            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
        }
    };

说明如下:

  1. 线程池中的工作线程少于CPU_COUNT+ 1个时,将会创建新的工作线程执行异步任务。
  • 线程池中已有CPU_COUNT + 1个工作线程但缓存队列(sPoolWorkQueue)未满,异步任务将会放到缓存队列中。
  • 线程池中已有CPU_COUNT+ 1个工作线程且缓存队列已满时,将会继续新的工作线程执行异步任务。
  • 线程池中已有CPU_COUNT * 2 + 1个工作线程池且缓存队列已满时,如果继续提交异步任务,将触发reject方法,由于AsyncTask使用的是默认的AbortPolicy,将会触发RejectException。

主要参考ThreadPoolExecutor.java中代码:

public void execute(Runnable command) {
     if (command == null)
        throw new NullPointerException();
/*
 * Proceed in 3 steps:
 *
 * 1. If fewer than corePoolSize threads are running, try to
 * start a new thread with the given command as its first
 * task.  The call to addWorker atomically checks runState and
 * workerCount, and so prevents false alarms that would add
 * threads when it shouldn't, by returning false.
 *
 * 2. If a task can be successfully queued, then we still need
 * to double-check whether we should have added a thread
 * (because existing ones died since last checking) or that
 * the pool shut down since entry into this method. So we
 * recheck state and if necessary roll back the enqueuing if
 * stopped, or start a new thread if there are none.
 *
 * 3. If we cannot queue task, then we try to add a new
 * thread.  If it fails, we know we are shut down or saturated
 * and so reject the task.
 */
    int c = ctl.get();
    if (workerCountOf(c) < corePoolSize) {
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    if (isRunning(c) && workQueue.offer(command)) {
        int recheck = ctl.get();
        if (! isRunning(recheck) && remove(command))
            reject(command);
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
    else if (!addWorker(command, false))
        reject(command);
}

以上英文注释也介绍了这一点。

    原文作者:Penner
    原文地址: https://www.jianshu.com/p/3596e7f36528
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞