如何在AsyncTask doInBackground()中使用同步对象?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在AsyncTask doInBackground()中使用同步对象?相关的知识,希望对你有一定的参考价值。
我在后台线程中使用synchronized对象时遇到了麻烦。我在样本简介中指定了问题:
- 我写这样简单的类:
public class UIThreadClass { MyObject object; UIThreadClass() { object = new MyObject(); object.doActionOne(); object.doActionTwo(); } }
- 现在我的任务是通过将两个方法放到非UI线程来改进代码。我正在使用AsyncTask
对于doActionOne()
private static class DoActionOneTask extends AsyncTask<Void, Void, Void> { private WeakReference<MyObject> wObject; DoActionOneTask(MyObject object) { wObject = new WeakReference<>(object); } @Override protected Void doInBackground(Void... voids) { if(wObject.get() != null) { MyObject myObject = wObject.get(); myObject.doActionOne(); } return null; } }
对于doActionTwo()private static class DoActionTwoTask extends AsyncTask<Void, Void, Void> { private WeakReference<MyObject> wObject; DoActionOneTask(MyObject object) { wObject = new WeakReference<>(object); } @Override protected Void doInBackground(Void... voids) { if(wObject.get() != null) { MyObject myObject = wObject.get(); myObject.doActionTwo(); } return null; } }
现在在UI线程中调用它们public class UIThreadClass { MyObject object; UIThreadClass() { object = new MyObject(); new DoActionOneTask(object).execute(); new DoActionTwoTask(object).execute(); } }
问题是:
使用AsyncTask时 - 如何同步对象以确保在doActionOne()方法之后总是调用doActionTwo()?
我尝试在doInBackground()中使用synchronized(myObject){myObject.doActionOne();}但是系统警告我myObject只是局部变量而且很难保证正确性。
任何人都可以帮我这种情况吗?非常感谢!
答案
你不需要做任何事情。它们将按照android文档顺序执行
Order of execution
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.
以上是关于如何在AsyncTask doInBackground()中使用同步对象?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 android 中将 asynctask 代码更改为 rxandroid 代码?
在 Android 中,如何从 AsyncTask 更改 TextView? [复制]