如何AsyncTask的SerialExecutor工作? [英] How does AsyncTask SerialExecutor work?

查看:121
本文介绍了如何AsyncTask的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);
        }
    }
}

以上code段是从执行SerialExcutor的AsyncTask的源$ C ​​$ C,但我不明白它究竟是如何工作的。

Above code snippet is from the AsyncTask source code implementing the SerialExcutor, But I dont understand how exactly it works.

当新任务到达时,它被放入ArrayDeque的端部,在ArrayDeque顶部的任务得到执行时,才会有当前正在执行的任何其他任务。 (当mActive == NULL)。

when a new task arrives, it is put into the end of a ArrayDeque, the task on the top of the ArrayDeque get executed only when there is no other task is being executed currently. (when mActive == null).

因此​​,如果正在执行任务时新任务到达,没有什么会被触发,当任务完成执行时,ArrayDeque怎么知道流行顶部的下一个任务来执行它???

So if a task is being executed when a new task arrive, there is nothing will be triggered, when the task finish executing, how the ArrayDeque know pop the next task on the top to execute it???

推荐答案

任务是由 THREAD_POOL_EXECUTOR 上一个单独的线程执行的需要在的Runnable 。在这种的Runnable 时,正在运行的任务完成出于某种原因, scheduleNext()是所谓的最后块。如果在队列中的任何任务,第一个会被执行,否则执行者将闲置,直到下一次调用的execute()。此外,同步确保的execute() scheduleNext()不能在单独的线程在同一时间运行。

Tasks are executed on a separate thread by THREAD_POOL_EXECUTOR that takes in a Runnable. In this Runnable, when the running task finishes for some reason, scheduleNext() is called in the finally block. If there are any tasks in the queue, the first one will be executed, otherwise the executor will be idle until the next call to execute(). Also, synchronized ensures that execute() and scheduleNext() cannot be run in separate threads at the same time.

这篇关于如何AsyncTask的SerialExecutor工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆