Asynctask解析以及注意事项

/*
    说到AsyncTask这个类,好多人其实不太了解。最近看了下代码,把心得分享给大家。
    AsyncTask的execute的执行流程为
    先调用ThreadPoolExecutor.execute(mFuture);
    然后ThreadPoolExecutor.execute(mFuture) 会调用ThreadPoolExecutor.addWorker(mFuture);
    最后ThreadPoolExecutor.addWorker(mFuture)会调用mFuture的run()方法,run方法中就是该线程要执行操作的地方
    到此我们来关注一下mFuture,AsyncTask中的mFuture是一个FutureTask,FutureTask实现了Future<V>, Runnable两个接口,
    Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果,计算完成后只能使用 get 方法来获取结果。
    mFuture以mWorker作为参数
    现看mFuture的构造方法:
public void run() {
    sync.innerRun();
}

    sync是什么呢?Sync类是一个内部类,我们看看它的初始化
public FutureTask(Callable<V> callable) {
    if (callable == null)
        throw new NullPointerException();
    sync = new Sync(callable);
}
    在看看sync.innerRun()方法:
void innerRun() {
    if (!compareAndSetState(READY, RUNNING))
        return;

    runner = Thread.currentThread();
    if (getState() == RUNNING) { // recheck after setting thread
        V result;
        try {
            result = callable.call();
        } catch (Throwable ex) {
            setException(ex);
            return;
        }
        set(result);
    } else {
        releaseShared(0); // cancel
    }
}
    从代码可以看到,其实最终是调用了callable.call()这个方法。
    从AsyncTask中我们可以知道,我们传入的Callable是我们的WorkerRunnable
    所以,我们会调用WorkerRunnable的call()方法,在call方法里面
    返回postResult(doInBackground(mParams));
    通知UI线程更新,这就是调用过程
Notes:
1:
    因为AsyncTask里面的内部handler和Executor都是静态变量,所以,他们控制着所有的子类。
2:
    我们可以通过AsyncTask.execute()方法来调用系统默认的线程池来处理当前的任务,
    系统默认的线程池用的是SerialExecutor.这个线程池控制所有任务按顺序执行。也就是一次只执行一条.
    当前执行完了,才执行下一条.2.3平台以前是所有的任务并发执行,这会导致一种情况,就是其中一条任务执行出问题了,会引起其他任务
    出现错误.
3:
    AsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)你也可以采用这个系统提供的线程池来处理你的任务
    默认这个线程池是并发处理任务的,也就是不按顺序来.核心为5条,最大128条
4:
    你也可以使用自定义的线程池,这样就可以即使的执行你的任务需求,而不是用系统的。因为用系统默认的线程池可以需要等待,它默认
    是按顺序执行(THREAD_POOL_EXECUTOR)或者最多执行5个(SerialExecutor).
    自己使用自定义线程池方式如下:
    new AsyncTask.executeOnExecutor((ExecutorService)Executors.newCachedThreadPool()).
5:  不要随意使用AsyncTask,除非你必须要与UI线程交互.默认情况下使用Thread即可,要注意需要将线程优先级调低.
    从google官方文档你也可以看到,AsyncTasks should ideally be used for short operations (a few seconds at the most.)
    AsyncTask适合处理短时间的操作,长时间的操作,比如下载一个很大的视频,这就需要你使用自己的线程来下载,不管是断点下载还是其它的.
    当然,如果你需要开启自定义的很多线程来处理你的任务,切记你此时可以考虑自定义线程池
 */ 
public abstract class AsyncTask<Params, Progress, Result> {
    private static final String LOG_TAG = "AsyncTask";
    // 核心线程数是要
    private static final int CORE_POOL_SIZE = 5;
    // 最大线程数支持128
    private static final int MAXIMUM_POOL_SIZE = 128;
    // 这个参数的的意思是当前线程池里面的thread如果超过了规定的核心线程5,如果有线程的空闲时间超过了这个数值,
    // 数值的单位自己指定,就回收该线程的资源,达到动态调整线程池资源的目的.
    private static final int KEEP_ALIVE = 1;
    // ThreadFactory是用来在线程池中构建新线程的方法.可以看到每次构建一个方法,名字都不同.为"AsyncTask # 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());
        }
    };
    // 线程池所使用的缓冲队列.FIFO,它用于存放如果当前线程池中核心线程已满,此时来的任务都被放到缓冲队列中等待被处理.
    // 初始化容量为10
    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(10);

    /**
     * An {@link Executor} that can be used to execute tasks in parallel.
     */
    // 线程池的初始化,指定了核心线程5,最大线程128,超时1s,缓冲队列等, 你在使用asyncTask的时候,可以传入这个参数,
    // 就可以让多条线程并发的执行了.比如:executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
    public static final Executor THREAD_POOL_EXECUTOR
            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

    /**
     * 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 final int MESSAGE_POST_RESULT = 0x1;
    private static final int MESSAGE_POST_PROGRESS = 0x2;
    // 这个InternalHandler就是用来是UI线程打交道的。可以看到它是个静态的变量。也就是说谁第一次调用它,下一次另一个
    // 线程来调用,也不会实例话这个常量.关于这个handler,默认asynctask都是从主线程中调用的,所以,这个Handler默认
    // 获得了主线程的Looper,所以就能和主线程来交互. Notes:假如你在一个子线程中构建了自己的Looper并使用Asynctask,
    // 应该会出问题,因为此时这个Handler就属于子线程了,就不能去操控UI的操作.这应该算是AsyncTask的Bug.网上有人说
    // 在4.0上运行没问题,2.3会有问题,原因是因为4.0中的ActivityThread.main方法里面最先用主线程的Looper来初始化了这个
    // AsyncTask。理论上Asynctask应该判断当前的Looper如果不是MainThread的Looper的话,抛出异常,遗憾的是,
    // google没有考虑到这里,只是在文档中要求必须在主线程中调用,其实,很不好!
    private static final InternalHandler sHandler = new InternalHandler();

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    // 自定义的静态内部类
    private final WorkerRunnable<Params, Result> mWorker;
    // 其实就是也一个Runnable,实现了这个接口
    private final FutureTask<Result> mFuture;

    // 默认为pending状态。
    private volatile Status mStatus = Status.PENDING;
    // 原子操作,专门用来处理并发访问,就可以不用synchronized
    private final AtomicBoolean mCancelled = new AtomicBoolean();
    private final AtomicBoolean mTaskInvoked = new AtomicBoolean();

    private static class SerialExecutor implements Executor {
        // ArrayDeque是一个双向队列,我们来理解下这个线程池是如何做到一次只
        // 执行一条任务的.比如此时有多处先后都调用了AsyncTask.execute()方法,
        // 对第一条最先到的任务来说,首先自己被假如到了队列中,因为第一次mActive == null成立,
        // 所以执行THREAD_POOL_EXECUTOR.execute(mActive).且mActive 此时不等于Null.
        // 所以第二条任务来的时候,只是被加入到了队列中,并不会执行.除非第一条任务执行完了,在它的finnally方法中
        // 调用scheduleNext()去再次从对列中取出下一条任务来执行.这样就实现了所有任务按顺序执行的功能.
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        Runnable mActive;

        public synchronized void execute(final Runnable r) {
            // 把线程offer到队列中
            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);
            }
        }
    }

    /**
     * Indicates the current status of the task. Each status will be set only once
     * during the lifetime of a task.
     */
    public enum Status {
        /**
         * Indicates that the task has not been executed yet.
         */
        PENDING,
        /**
         * Indicates that the task is running.
         */
        RUNNING,
        /**
         * Indicates that {@link AsyncTask#onPostExecute} has finished.
         */
        FINISHED,
    }

    /** @hide Used to force static handler to be created. */
    public static void init() {
        sHandler.getLooper();
    }

    /** @hide */
    public static void setDefaultExecutor(Executor exec) {
        sDefaultExecutor = exec;
    }

    /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     */
    public AsyncTask() {
        //初始化mWorker并复写call方法,后面会介绍什么时候调用
        mWorker = new WorkerRunnable<Params, Result>() {
            // 这个方法就是当你嗲用excutor.excute()方法后执行的方法。至于是如何执行的,我们后面会分析
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                // 将线程优先级设置为后台线程,默认和主线程优先级一样,如果不这样做,也会降低程序性能.因为会优先
                // 抢占cpu资源.所以,如果你在程序中不使用asyncTask而是自己new 一条线程出来,记得把线程的优先级设置为
                // 后台线程
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //这个地方调用了我们自己实现的doInBackground
                return postResult(doInBackground(mParams));
            }
        };
       // 用mWorker创建一个可取消的异步计算任务
        mFuture = new FutureTask<Result>(mWorker) {
            @Override
            // 当任务不管是正常终止、异常或取消而完成的,都回调此方法, 即isDone()为true时,isDone不管成功还是失败都
            // 返回true
            protected void done() {
                try {
                    // 如果当前的task没有被invoke,就被finish掉
                    postResultIfNotInvoked(get());
                } catch (InterruptedException e) {
                    android.util.Log.w(LOG_TAG, e);
                } catch (ExecutionException e) {
                    throw new RuntimeException("An error occured while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };
    }

    private void postResultIfNotInvoked(Result result) {
        final boolean wasTaskInvoked = mTaskInvoked.get();
        if (!wasTaskInvoked) {
            postResult(result);
        }
    }

    // 当doInBackground结束了,调用PostResult发布结果
    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }

    /**
     * Returns the current status of this task.
     *
     * @return The current status.
     */
    // 获得当前的状态
    public final Status getStatus() {
        return mStatus;
    }

    /**
     * Override this method to perform a computation on a background thread. The
     * specified parameters are the parameters passed to {@link #execute}
     * by the caller of this task.
     *
     * This method can call {@link #publishProgress} to publish updates
     * on the UI thread.
     *
     * @param params The parameters of the task.
     *
     * @return A result, defined by the subclass of this task.
     *
     * @see #onPreExecute()
     * @see #onPostExecute
     * @see #publishProgress
     */
    // 用户自己实现
    protected abstract Result doInBackground(Params... params);

    /**
     * Runs on the UI thread before {@link #doInBackground}.
     *
     * @see #onPostExecute
     * @see #doInBackground
     */
    // 用户自己实现
    protected void onPreExecute() {
    }

    /**
     * <p>Runs on the UI thread after {@link #doInBackground}. The
     * specified result is the value returned by {@link #doInBackground}.</p>
     *
     * <p>This method won't be invoked if the task was cancelled.</p>
     *
     * @param result The result of the operation computed by {@link #doInBackground}.
     *
     * @see #onPreExecute
     * @see #doInBackground
     * @see #onCancelled(Object)
     */
    @SuppressWarnings({"UnusedDeclaration"})
    // 用户自己实现
    protected void onPostExecute(Result result) {
    }

    /**
     * Runs on the UI thread after {@link #publishProgress} is invoked.
     * The specified values are the values passed to {@link #publishProgress}.
     *
     * @param values The values indicating progress.
     *
     * @see #publishProgress
     * @see #doInBackground
     */
    @SuppressWarnings({"UnusedDeclaration"})
    // 用户自己实现
    protected void onProgressUpdate(Progress... values) {
    }

    /**
     * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
     * {@link #doInBackground(Object[])} has finished.</p>
     *
     * <p>The default implementation simply invokes {@link #onCancelled()} and
     * ignores the result. If you write your own implementation, do not call
     * <code>super.onCancelled(result)</code>.</p>
     *
     * @param result The result, if any, computed in
     *               {@link #doInBackground(Object[])}, can be null
     *
     * @see #cancel(boolean)
     * @see #isCancelled()
     */
    @SuppressWarnings({"UnusedParameters"})
    protected void onCancelled(Result result) {
        onCancelled();
    }

    /**
     * <p>Applications should preferably override {@link #onCancelled(Object)}.
     * This method is invoked by the default implementation of
     * {@link #onCancelled(Object)}.</p>
     *
     * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
     * {@link #doInBackground(Object[])} has finished.</p>
     *
     * @see #onCancelled(Object)
     * @see #cancel(boolean)
     * @see #isCancelled()
     */
    protected void onCancelled() {
    }

    /**
     * Returns <tt>true</tt> if this task was cancelled before it completed
     * normally. If you are calling {@link #cancel(boolean)} on the task,
     * the value returned by this method should be checked periodically from
     * {@link #doInBackground(Object[])} to end the task as soon as possible.
     *
     * @return <tt>true</tt> if task was cancelled before it completed
     *
     * @see #cancel(boolean)
     */
    public final boolean isCancelled() {
        return mCancelled.get();
    }

    /**
     * <p>Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when <tt>cancel</tt> is called,
     * this task should never run. If the task has already started,
     * then the <tt>mayInterruptIfRunning</tt> parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.</p>
     *
     * <p>Calling this method will result in {@link #onCancelled(Object)} being
     * invoked on the UI thread after {@link #doInBackground(Object[])}
     * returns. Calling this method guarantees that {@link #onPostExecute(Object)}
     * is never invoked. After invoking this method, you should check the
     * value returned by {@link #isCancelled()} periodically from
     * {@link #doInBackground(Object[])} to finish the task as early as
     * possible.</p>
     *
     * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
     *        task should be interrupted; otherwise, in-progress tasks are allowed
     *        to complete.
     *
     * @return <tt>false</tt> if the task could not be cancelled,
     *         typically because it has already completed normally;
     *         <tt>true</tt> otherwise
     *
     * @see #isCancelled()
     * @see #onCancelled(Object)
     */
    public final boolean cancel(boolean mayInterruptIfRunning) {
        mCancelled.set(true);
        return mFuture.cancel(mayInterruptIfRunning);
    }

    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *
     * @return The computed result.
     *
     * @throws CancellationException If the computation was cancelled.
     * @throws ExecutionException If the computation threw an exception.
     * @throws InterruptedException If the current thread was interrupted
     *         while waiting.
     */
    public final Result get() throws InterruptedException, ExecutionException {
        return mFuture.get();
    }

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result.
     *
     * @param timeout Time to wait before cancelling the operation.
     * @param unit The time unit for the timeout.
     *
     * @return The computed result.
     *
     * @throws CancellationException If the computation was cancelled.
     * @throws ExecutionException If the computation threw an exception.
     * @throws InterruptedException If the current thread was interrupted
     *         while waiting.
     * @throws TimeoutException If the wait timed out.
     */
    public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
            ExecutionException, TimeoutException {
        return mFuture.get(timeout, unit);
    }

    /**
     * Executes the task with the specified parameters. The task returns
     * itself (this) so that the caller can keep a reference to it.
     *
     * <p>Note: this function schedules the task on a queue for a single background
     * thread or pool of threads depending on the platform version.  When first
     * introduced, AsyncTasks were executed serially on a single background thread.
     * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
     * to a pool of threads allowing multiple tasks to operate in parallel. Starting
     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being
     * executed on a single thread to avoid common application errors caused
     * by parallel execution.  If you truly want parallel execution, you can use
     * the {@link #executeOnExecutor} version of this method
     * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
     * on its use.
     *
     * <p>This method must be invoked on the UI thread.
     *
     * @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 #executeOnExecutor(java.util.concurrent.Executor, Object[])
     * @see #execute(Runnable)
     */
    // 这个方法就是用户调用的excute方法,默认采用asynctask自带的线程池串行执行任务
    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[])
     */
    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;
        // 调用用户--UI线程---自己实现的方法
        onPreExecute();

        mWorker.mParams = params;
        // 这个方法就会调用前面的mWorker的call方法
        exec.execute(mFuture);

        return this;
    }

    /**
     * Convenience version of {@link #execute(Object...)} for use with
     * a simple Runnable object. See {@link #execute(Object[])} for more
     * information on the order of execution.
     *
     * @see #execute(Object[])
     * @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
     */
    public static void execute(Runnable runnable) {
        sDefaultExecutor.execute(runnable);
    }

    /**
     * This method can be invoked from {@link #doInBackground} to
     * publish updates on the UI thread while the background computation is
     * still running. Each call to this method will trigger the execution of
     * {@link #onProgressUpdate} on the UI thread.
     *
     * {@link #onProgressUpdate} will note be called if the task has been
     * canceled.
     *
     * @param values The progress values to update the UI with.
     *
     * @see #onProgressUpdate
     * @see #doInBackground
     */
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }

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

    //  与UI交互
    private static class InternalHandler extends Handler {
        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
        @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 static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }

    @SuppressWarnings({"RawUseOfParameterizedType"})
    // 存储异步执行结果的类
    private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;

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


  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值