Android基础进阶知识

Android线程和线程池---AsyncTask源码分析

2017-07-02  本文已影响15人  i冰点

1、AsyncTask源码分析

1、构造方法

先看构造方法,在类初始化的时候,创建了Callable对象和FutureTask对象,并用FutureTask对象来包装Callable对象,call()方法将做为线程的执行体。

    private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }
    public AsyncTask() {
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                //当前任务已被调用过
                mTaskInvoked.set(true);
                try {
                    ...
                    result = doInBackground(mParams);
                } catch (Throwable tr) {
                    ...
                } finally {
                    postResult(result);
                }
                return result;
            }
        };

        mFuture = new FutureTask<Result>(mWorker) {...};
    }

但是为什么要使用FutureTask和Callable,直接使用Runnable不可以吗?

2、InternalHandler

postResult()方法会通过InternalHandler,向主线程发送一个MESSAGE_POST_RESULT消息;InternalHandler收到消息后,会调用AsyncTask的finish()方法,然后就可以将结果传递给onPostExecute()方法了。

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

InternalHandler,用于将执行环境从线程池,切换到主线程

    private static Handler getHandler() {
        synchronized (AsyncTask.class) {
            if (sHandler == null) {
                sHandler = new InternalHandler();
            }
            return sHandler;
        }
    }

    private static class InternalHandler extends Handler {
        public InternalHandler() {
            super(Looper.getMainLooper());
        }
        @Override
        public void handleMessage(Message msg) {
            AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
            switch (msg.what) {
                case MESSAGE_POST_RESULT:
                    // There is only one result
                    result.mTask.finish(result.mData[0]);
                    break;
                case MESSAGE_POST_PROGRESS:
                    result.mTask.onProgressUpdate(result.mData);
                    break;
            }
        }
    }

    private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }

    private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;

        AsyncTaskResult(AsyncTask task, Data... data) {
            mTask = task;
            mData = data;
        }
    }

从以上代码中我们可以看到,sHandler是一个静态的Handler对象。我们知道创建Handler对象时需要当前线程的Looper,所以我们为了以后能够通过sHandler将执行环境从后台线程切换到主线程(即在主线程中执行handleMessage方法),我们必须使用主线程的Looper,因此必须在主线程中创建sHandler。这也就解释了为什么必须在主线程中加载AsyncTask类,是为了完成sHandler这个静态成员的初始化工作。

3、execute()方法

execute()方法接收的参数是Params类型的参数,这个参数会一路传递到doInBackground方法中;通过execute()方法,可以将FutureTask对象添加到线程池(SerialExecutor)中

    @MainThread
    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }

如下,当AsyncTask对象的当前状态为RUNNING或FINISHED时,调用execute方法会抛出异常,这意味着不能对正在执行任务的AsyncTask对象或是已经执行完任务的AsyncTask对象调用execute方法,这就是‘一个AsyncTask对象只能调用一次execute方法’的原因

    @MainThread
    public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
            Params... params) {
        if (mStatus != Status.PENDING) {
            switch (mStatus) {
                case RUNNING:
                    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;
    }

AsyncTask有两个线程池:sDefaultExecutor (SerialExecutor)、THREAD_POOL_EXECUTOR。
sDefaultExecutor,是一个串行的线程池,主要是把任务加到任务缓存队列中;THREAD_POOL_EXECUTOR用于真正的执行任务

THREAD_POOL_EXECUTOR线程池,会执行mTasks中的run()方法——>mFuture的run()方法——>Callable的call()方法——>doInBackground()方法

    private static volatile Executor sDefaultExecutor = new SerialExecutor();
    private static class SerialExecutor implements Executor {
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        Runnable mActive;

        public synchronized void execute(final Runnable r) {
            mTasks.offer(new Runnable() {
                public void run() {
                    try {
                        r.run();
                    } finally {
                        scheduleNext();
                    }
                }
            });
            if (mActive == null) {
                scheduleNext();
            }
        }

        protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }
    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);
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        THREAD_POOL_EXECUTOR = threadPoolExecutor;
    }

2、AsyncTask的简单使用

        AsyncTask asyncTask=new AsyncTask<String, Integer, Void>() {
            @Override
            protected void onPreExecute() {}
            @Override
            protected void onPostExecute(Void aVoid) { }
            @Override
            protected void onProgressUpdate(Integer... values) {}
            @Override
            protected Void doInBackground(String... params) { return null;}}
      .execute("");

3、 AsyncTask的局限性

AsyncTask的优点在于执行完后台任务后可以很方便的更新UI,然而使用它存在着诸多的限制

</br></br>

参考:Android开发艺术探讨深入理解AsyncTask的工作原理

</br></br>

上一篇 下一篇

猜你喜欢

热点阅读