【问题标题】:Threading rules AsyncTask线程规则 AsyncTask
【发布时间】:2019-02-20 08:24:30
【问题描述】:

AsyncTask 有 5 个线程规则:

这个类必须遵循一些线程规则 正常工作:

  1. 必须在 UI 线程上加载 AsyncTask 类。这个做完了 从 Build.VERSION_CODES.JELLY_BEAN 自动开始。

  2. 任务实例必须在 UI 线程上创建。

  3. execute(Params...) 必须在 UI 线程上调用。

  4. 不要调用 onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) 手动。

  5. 任务只能执行一次(如果执行 尝试第二次执行。)

但是,我不太了解规则 2 和 3。我已经在以下代码上尝试过它们:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    log(Thread.currentThread().getName());

    new Thread(new Runnable() {
        @Override
        public void run() {
            log(Thread.currentThread().getName());
            Task task = new Task();
            task.execute();
        }
    }).start();
}

public class Task extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... voids) {
        return null;
    }
}

结果如下:

09-15 21:27:10.179 3310-3310/com.xxx.test D/com.xxx.test.MainActivity: main
09-15 21:27:10.179 3310-3329/com.xxx.test D/com.xxx.test.MainActivity: Thread-264

我有一个问题: 为什么我可以创建任务实例并在除 UI 线程(主)之外的另一个线程(Thread-264)中调用execute() 方法?

我阅读了this post,但没有解释原因。非常感谢!

【问题讨论】:

    标签: android multithreading android-asynctask


    【解决方案1】:

    来自Android official site

    异步任务由运行在 后台线程,其结果发布在 UI 线程上。

    有些地方我们需要澄清。

    1. 我们的计算将在后台线程上运行
    2. 计算结果将在 UI 线程上发布
    3. 它们不会阻止开发人员从非 UI 线程创建或调用 AsyncTask

    第 1 步:打电话时

    Task task = new Task();
    

    看看AsyncTask source code

    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);
                }
            }
        };
    }
    

    首先他们创建一个引用 UI 线程的处理程序的处理程序,然后创建一个调用 doInBackground 方法的 Runnable(我们这里的计算),然后返回一个 Future(将在将来的某个时间返回计算结果) .

    第 2 步:然后调用

    task.execute();
    

    看看AsyncTask source code

    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;
    }
    

    onPreExecute() 将在调用 AsyncTask 的调用线程(在本例中为您的匿名线程)上调用。然后它在其 executor 中执行 Future。

    计算完成后会调用postResult方法。

    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }
    
    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:
                    // 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;
    }
    

    getHandler 在这种情况下指的是 UI 线程的处理程序,因此 onPostExecute 将始终在 UI 线程上调用。

    结论:

    AsyncTask 允许正确且轻松地使用 UI 线程。这节课 允许您执行后台操作并在 无需操作线程和/或处理程序的 UI 线程。

    【讨论】:

    • 谢谢 bạn nhiều,它帮助我了解更多。
    【解决方案2】:

    用户代码可以期望它们从 UI 运行 3 种保护方法

    1. onPreExecute()
    2. onProgressUpdate(Progress...)
    3. onPostExecute(Result)

    虽然onPreExecute() 将在调用execute() 的任何线程上运行,但其余2 个方法将由Handler 运行。

    Handler 类将与创建它的线程相关联,它允许用户代码发布 Runable 以在该特定线程上运行。在AsyncTask 出现之前,想要更新UI(必须在UI 线程上更新)的用户代码必须首先在UI 线程上创建Handler,然后将Runable 发布到Handler 以在UI 线程上执行他们的任务.

    AsyncTask 旨在简化那些繁琐的工作,它们的内部静态 Handler 由 UI/主线程在创建 AsyncTask 实例之前创建。

    即使您可以在工作线程中使用AsyncTaskonPreExecute() 除外),我建议您按照文档并在 UI 线程上创建/运行 AsyncTask

    【讨论】:

    • @NguyễnVănQuang 如果此答案或任何其他答案解决了您的问题,请将其标记为已接受。
    猜你喜欢
    • 2021-11-01
    • 2011-02-12
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 2012-03-28
    • 2012-09-14
    • 2011-12-02
    • 2016-04-18
    相关资源
    最近更新 更多