我在后台线程中使用synchronized对象时遇到了麻烦。我在样本简介中指定了问题:
public class UIThreadClass {
MyObject object;
UIThreadClass() {
object = new MyObject();
object.doActionOne();
object.doActionTwo();
}
}
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.