AsyncTask使用及内部实现分析

一、使用方法

AsyncTask通常用于实现在后台线程中完成耗时操作,然后在主线程中更新UI。

继承AsyncTask需要指定3个泛型参数:
AsyncTask<Params, Progress, Result>

  • Params: 启动任务执行的输入参数的类型
  • Progress: 后台任务完成的进度值得类型
  • Result: 后台执行任务完成后返回结果的类型

使用AsyncTask的主要方法:

  • protected String doInBackground(Params... params)
    在后台线程池中执行,可以调用publishProgress(Progress... values)方法触发onProgressUpdate方法,从而更新任务任务进度
  • protected void onProgressUpdate(Progress... values)
    在UI线程执行,更新进度条等UI
  • protected void onPreExecute()
    在doInBackground方法之前UI线程执行,通常用于完成初始化工作。
  • protected void onPostExecute(Result result)
    在UI线程执行,在doInBackground方法之后会自动调用,并将doInBackground的返回值传给该方法。

使用AsyncTask必须遵守以下原则:

  • 必须在UI线程创建AsyncTask实例,API26之后不需要
  • 必须在UI线程中调用AsyncTask的execute()方法,因为onPreExecute需要在主线程回调
  • 每个AsyncTask在后台任务执行完成前只能被执行一次,多次调用会引发异常

demo

public class MainActivity extends AppCompatActivity {
    private TextView show = null;
    private Button button = null;
    private final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        show = (TextView)findViewById(R.id.show);
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    download();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void download() throws MalformedURLException {
        MyAsyncTask task = new MyAsyncTask(this);
        //AsyncTask第一个参数为Void,如果不是Void,execute方法需要传入参数。
        task.execute();
    }




    class MyAsyncTask extends AsyncTask<Void, Integer, String> {

        ProgressDialog pDialog;
        int hasRead = 0;
        Context mContext;
        public MyAsyncTask(Context context) {
            mContext = context;
        }

        @Override
        protected String doInBackground(Void... params) {
            StringBuilder sb = new StringBuilder();
            try{
                while (hasRead < 100) {
                    hasRead++;
                    sb.append(hasRead + " ");
                    publishProgress(hasRead);
                    Thread.sleep(200);
                }
                return sb.toString();
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }



        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(mContext);
            pDialog.setTitle("任务正在执行中");
            pDialog.setMessage("任务正在执行中, 敬请等待...");
            pDialog.setCancelable(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setIndeterminate(false);
            pDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            show.setText("已经读取了【" + values[0] + "】行!");
            pDialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            show.setText(s);
            if (hasRead == 100) {
                pDialog.dismiss();
            }

        }
    }
}

[图片上传失败...(image-c5125d-1551414183649)]
AsyncTaskTest.jpg

二、AsyncTask源码分析

首先来看下构造函数

/frameworks/base/core/java/android/os/AsyncTask.java

     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     */
    public AsyncTask() {
        this((Looper) null);
    }

    /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     *
     * @hide
     */
    public AsyncTask(@Nullable Handler handler) {
        this(handler != null ? handler.getLooper() : null);
    }

    /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     *
     * @hide
     */
    public AsyncTask(@Nullable Looper callbackLooper) {
        mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);

        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                Result result = null;
                try {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    postResult(result);
                }
                return result;
            }
        };

        mFuture = new FutureTask<Result>(mWorker) {
            @Override
            protected void done() {
                try {
                    postResultIfNotInvoked(get());
                } catch (InterruptedException e) {
                    android.util.Log.w(LOG_TAG, e);
                } catch (ExecutionException e) {
                    throw new RuntimeException("An error occurred while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };
    }

构造函数中首先创建了一个WorkerRunnable对象,我们看下WorkerRunnable定义:

    private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }

WorkerRunnable继承自Callable接口,Callable接口跟Runnable接口类似,只是其中的call方法带返回值

public interface Runnable {
    public abstract void run();
}

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

回到AsyncTask构造函数中,在WorkerRunnable的call方法中调用了doInBackground,doInBackground执行完后把结果传给postResult方法。继续往下看创建了FutureTask对象,FutureTask可以通过调用ExecutorService.submit执行参数Callable中的任务,也可以用于获得Callable任务的执行结果、查询是否完成和取消任务等操作。所以AsyncTask构造函数中主要工作是:

  1. 在一个Callable对象mWorker的call方法中,调用doInBackground方法,并将结果传给postResult方法
  2. 创建以mWorker作为参数的FutureTask对象mFuture。

接下来再看AsyncTask.execute()方法:

    @MainThread
    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }
    /**
     * Executes the task with the specified parameters. The task returns
     * itself (this) so that the caller can keep a reference to it.
     *
     * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
     * allow multiple tasks to run in parallel on a pool of threads managed by
     * AsyncTask, however you can also use your own {@link Executor} for custom
     * behavior.
     *
     * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
     * a thread pool is generally <em>not</em> what one wants, because the order
     * of their operation is not defined.  For example, if these tasks are used
     * to modify any state in common (such as writing a file due to a button click),
     * there are no guarantees on the order of the modifications.
     * Without careful work it is possible in rare cases for the newer version
     * of the data to be over-written by an older one, leading to obscure data
     * loss and stability issues.  Such changes are best
     * executed in serial; to guarantee such work is serialized regardless of
     * platform version you can use this function with {@link #SERIAL_EXECUTOR}.
     *
     * <p>This method must be invoked on the UI thread.
     *
     * @param exec The executor to use.  {@link #THREAD_POOL_EXECUTOR} is available as a
     *              convenient process-wide thread pool for tasks that are loosely coupled.
     * @param params The parameters of the task.
     *
     * @return This instance of AsyncTask.
     *
     * @throws IllegalStateException If {@link #getStatus()} returns either
     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
     *
     * @see #execute(Object[])
     */
    @MainThread
    public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
            Params... params) {
        if (mStatus != Status.PENDING) {
            switch (mStatus) {
                case RUNNING:
                    //如果任务没有结束mStatus状态为RUNNING,则会抛出异常,所以每个AsyncTask在后台任务执行完成前只能被执行一次,多次调用会引发异常
                    throw new IllegalStateException("Cannot execute task:"
                            + " the task is already running.");
                case FINISHED:
                    throw new IllegalStateException("Cannot execute task:"
                            + " the task has already been executed "
                            + "(a task can be executed only once)");
            }
        }

        mStatus = Status.RUNNING;

        onPreExecute();

        mWorker.mParams = params;
        exec.execute(mFuture);

        return this;
    }

execute() 方法直接调用executeOnExecutor传入默认的sDefaultExecutor,是串行Executor,executeOnExecutor()方法首先回调onPreExecute(),然后调用sDefaultExecutor.execute()执行构造函数中的Callable任务mWorker,下面看下sDefaultExecutor的定义:

    /**
     * An {@link Executor} that executes tasks one at a time in serial
     * order.  This serialization is global to a particular process.
     */
    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    private static class SerialExecutor implements Executor {
        //Runnable缓存队列
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        //mActive正在执行的Runnable
        Runnable mActive;

        public synchronized void execute(final Runnable r) {
            mTasks.offer(new Runnable() {
                public void run() {
                    try {
                        //mFuture的run()方法会调用mWorker的call()方法
                        r.run();
                    } finally {
                        //执行完一个任务后再从缓存队列中取下一个
                        scheduleNext();
                    }
                }
            });
            //第一次mActive为null,直接调用scheduleNext
            if (mActive == null) {
                scheduleNext();
            }
        }

        protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
                //真正在线程池中开始执行任务
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }

SerialExecutor主要作用请参考注释,其实SerialExecutor的作用是保证来的线程是串行执行的,真正在后台开始执行任务是THREAD_POOL_EXECUTOR.execute(mActive)

    private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE_SECONDS = 30;

    //用于创建线程池总的线程
    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());
        }
    };
    //缓存队列,用来存储执行的任务,基于链表的先进先出队列,这里指定长度为128
    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);

    /**
     * An {@link Executor} that can be used to execute tasks in parallel.
     */
    public static final Executor THREAD_POOL_EXECUTOR;

    static {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
                sPoolWorkQueue, sThreadFactory);
        //但是如果调用了allowCoreThreadTimeOut(boolean)方法,在线程池中的线程数不大于corePoolSize时,keepAliveTime参数也会起作用,直到线程池中的线程数为0;
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        THREAD_POOL_EXECUTOR = threadPoolExecutor;
    }

java.uitl.concurrent.ThreadPoolExecutor类是线程池中最核心的一个类,这里创建ThreadPoolExecutor对象的几个重要参数:

  • CORE_POOL_SIZE
    线程池中的核心线程个数,当线程池中线程数小于CORE_POOL_SIZE时,进来新任务就创建线程,当大于CORE_POOL_SIZE时,则放入缓存队列中,这里定义为2到4个。
  • MAXIMUM_POOL_SIZE
    线程池中最大线程个数,当缓存队列已满或者任务剧增时,最多可以创建的线程个数,这里为 CPU_COUNT * 2 + 1
  • KEEP_ALIVE_SECONDS
    表示线程没有任务执行时最多保持多久时间会终止。默认情况下,只有当线程池中的线程数大于corePoolSize时,keepAliveTime才会起作用,直到线程池中的线程数不大于corePoolSize,这里是30s
  • TimeUnit.SECONDS
    keepAliveTime的时间单位为s
  • sPoolWorkQueue
    线程池缓存队列
  • sThreadFactory
    线程工厂,用来创建线程

回到前面构造函数中执行完后台任务doInBackground,会调用postResult处理结果

    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }

这里getHandler()通常返回InternalHandler的静态实例sHandler

    private static InternalHandler sHandler;
    private static class InternalHandler extends Handler {
        public InternalHandler(Looper looper) {
            super(looper);
        }

        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
        @Override
        public void handleMessage(Message msg) {
            AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
            switch (msg.what) {
                case MESSAGE_POST_RESULT:
                    //这里回调onPostExecut
                    result.mTask.finish(result.mData[0]);
                    break;
                case MESSAGE_POST_PROGRESS:
                    result.mTask.onProgressUpdate(result.mData);
                    break;
            }
        }
    }

sHandler绑定的主线程的Looper,这就保证了onProgressUpdate和onPostExecute函数在主线程中回调

    private static Handler getMainHandler() {
        synchronized (AsyncTask.class) {
            if (sHandler == null) {
                sHandler = new InternalHandler(Looper.getMainLooper());
            }
            return sHandler;
        }
    }
  • 关于串行并行问题

    串行:

    直接调用execute方法使用默认的Executor: SERIAL_EXECUTOR,这是个静态实例,所以适用于以下有多个任务的情况下,保证串行执行

    MyAsyncTask task1 = new MyAsyncTask();
    MyAsyncTask task2 = new MyAsyncTask();
    MyAsyncTask task3 = new MyAsyncTask();
    ... ...
    task1.execute();
    task2.execute();
    task3.execute();
    
    

    并行:

    如果希望并行执行任务则需要调用方法executeOnExecutor(),传入参数Executor:THREAD_POOL_EXECUTOR

    MyAsyncTask task1 = new MyAsyncTask();
    MyAsyncTask task2 = new MyAsyncTask();
    MyAsyncTask task3 = new MyAsyncTask();
    ... ...
    task1.executeOnExecutor(THREAD_POOL_EXECUTOR,...);
    task2.executeOnExecutor(THREAD_POOL_EXECUTOR,...);
    task3.executeOnExecutor(THREAD_POOL_EXECUTOR,...);
    

三、参考文档

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