AsyncTask解析

AsyncTask解析

AsyncTask原理简介

  • AsyncTask通过Handler实现异步消息处理。
  • AsyncTask是一个抽象类,使用的时候必须要实现抽象方法doInBackground(Params… params),onPreExecute()和PostExecute(Result result)和onProgressUpdate(Progress… values)都是空方法,当业务需要的时候可以选择重写该方法。
  • AsyncTask初始化流程图

AsyncTask解析_第1张图片

  • AsyncTask执行流程图

AsyncTask解析_第2张图片
- AsyncTask默认单任务执行模式,同一时间只能有一个任务在执行。

关键源码解析


public abstract class AsyncTask {
    private static final String LOG_TAG = "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());
        }
    };

    private static final BlockingQueue sPoolWorkQueue =
            new LinkedBlockingQueue(128);

    // 线程池,静态变量,所有的AsyncTask对象共享
    public static final Executor THREAD_POOL_EXECUTOR
            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
            TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

    // 自定义Executor,保证同一时间只有一个任务执行,静态变量所有的AsyncTask对象共享
    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
    // 任务完成,消息标志
    private static final int MESSAGE_POST_RESULT = 0x1;
    // 任务进度,消息标志
    private static final int MESSAGE_POST_PROGRESS = 0x2;

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    private static InternalHandler sHandler;

    private final WorkerRunnable mWorker;
    private final FutureTask mFuture;
    // 表示任务当前的状态
    private volatile Status mStatus = Status.PENDING;

    private final AtomicBoolean mCancelled = new AtomicBoolean();
    private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
    // 自定义Executor,保证同一时间只有一个任务执行
    private static class SerialExecutor implements Executor {
        // 自增长队列,多线程不安全
        final ArrayDeque mTasks = new ArrayDeque();
        Runnable mActive;
        // 加锁
        public synchronized void execute(final Runnable r) {
            // 向队列中插入任务
            mTasks.offer(new Runnable() {
                public void run() {
                    try {
                        r.run();
                    } finally {
                        // 当前任务执行完毕后,执行下一个任务
                        scheduleNext();
                    }
                }
            });
            // mActive为null,代表当前没有任务执行,执行刚才插入队列的任务
            if (mActive == null) {
                scheduleNext();
            }
        }

        // 如果队列中没有任务,mActive则变为null;有任务则赋值给mActive,线程池来执行该任务
        protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }


    public enum Status {
        // 初始化状态
        PENDING,
       // 正在运行状态
        RUNNING,
        // 结束状态
        FINISHED,
    }

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

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

   // AsyncTask构造方法
public AsyncTask() {
        // 初始化Callable对象
        mWorker = new WorkerRunnable() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                // 调用doInBackground()方法
                Result result = doInBackground(mParams);
                Binder.flushPendingCommands();
                // 执行完毕发送结果
                return postResult(result);
            }
        };

        // 初始化FutureTask对象,mWorker传递进去
        mFuture = new FutureTask(mWorker) {
            @Override
            protected void done() {
                try {
                   //如果mWorker的call()异常未执行,在这边发送结果
                    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);
                }
            }
        };
    }

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

    // 发送任务完成消息
    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult(this, result));
        message.sendToTarget();
        return result;
    }


    public final Status getStatus() {
        return mStatus;
    }

    // 需要实现的方法,耗时操作的代码块
    protected abstract Result doInBackground(Params... params);

    // 任务开始前的回调方法体
    protected void onPreExecute() {
    }

    // 任务完成后回调方法体
    protected void onPostExecute(Result result) {
    }

    // 进度更新回调方法体
    protected void onProgressUpdate(Progress... values) {
    }

    // 任务取消回调方法体
    protected void onCancelled(Result result) {
        onCancelled();
    }


    protected void onCancelled() {
    }


    public final boolean isCancelled() {
        return mCancelled.get();
    }

    public final boolean cancel(boolean mayInterruptIfRunning) {
        mCancelled.set(true);
        return mFuture.cancel(mayInterruptIfRunning);
    }

    // 获取任务结果
    public final Result get() throws InterruptedException, ExecutionException {
        return mFuture.get();
    }

    // 获取任务结果,设置等待结果的超时时间
    public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
            ExecutionException, TimeoutException {
        return mFuture.get(timeout, unit);
    }

    // 开始执行任务,参数最终会传递给doInBackground(Params... params)方法
public final AsyncTask execute(Params... params) {
    // sDefaultExecutor默认是SerialExecutor对象,如果不希望同一时间只有一个任务在执行,可以设置sDefaultExecutor为自定义的Executor对象
    return executeOnExecutor(sDefaultExecutor, params);
}

    // 开始执行任务,参数最终会传递给doInBackground(Params... params)方法
public final AsyncTask execute(Params... params) {
    // sDefaultExecutor默认是具有单线程池效果的Executor对象(下面会分析该对象源码),如果不希望同一时间只有一个任务在执行,可以设置sDefaultExecutor为自定义的Executor对象
    return executeOnExecutor(sDefaultExecutor, params);
}

public final AsyncTask executeOnExecutor(Executor exec,
            Params... params) {
        // 如果不是初始状态,抛出异常。说明一个AsynyTask对象只能调用一次execute(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;
        // 线程池执行FutureTask对象
        exec.execute(mFuture);

        return this;
    }

    // 静态方法,可以当做单线程池来用
    public static void execute(Runnable runnable) {
        sDefaultExecutor.execute(runnable);
    }

    // 进度更新时,通过Handler发送通知
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult(this, values)).sendToTarget();
        }
    }

    private void finish(Result result) {
        if (isCancelled()) {
            // 回调取消方法体
            onCancelled(result);
        } else {
            // 回调任务结果方法体
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }

    // 静态Handler对象,所有的AsyncTask对象共用
    private static class InternalHandler extends Handler {
        public InternalHandler() {
            super(Looper.getMainLooper());
        }

        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
        @Override
        public void handleMessage(Message msg) {
            // 获取任务结果对象
            AsyncTaskResult result = (AsyncTaskResult) msg.obj;
            switch (msg.what) {
                // 接受到任务结束消息
                case MESSAGE_POST_RESULT:
                    // 回调结束方法
                    result.mTask.finish(result.mData[0]);
                    break;
                // 接受到任务进度更新消息
                case MESSAGE_POST_PROGRESS:
                   //回调进度更新方法
                    result.mTask.onProgressUpdate(result.mData);
                    break;
            }
        }
    }

    // 实现Callable接口,对比Runable接口,Callable接口有返回值
    private static abstract class WorkerRunnable implements Callable {
        Params[] mParams;
    }

    @SuppressWarnings({"RawUseOfParameterizedType"})
    private static class AsyncTaskResult {
        final AsyncTask mTask;
        final Data[] mData;

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

你可能感兴趣的:(android多线程,android)