我正在尝试实现 2 个异步任务,其中一个应该等待另一个完成。
我为它做了一个测试用例,看起来像这样:
public class MainActivity extends Activity{
public static boolean SYNCING = false;
public static Object LOCK = new Object();
public static void setSync(){
Log.i(TAG, "setting Sync=true");
synchronized (LOCK) {
SYNCING = true;
}
}
public static void waitForSync(){
Log.i(TAG, "waiting for Sync");
synchronized (LOCK) {
try{
while (SYNCING){
LOCK.wait();
}
} catch (InterruptedException ignore){}
}
}
public static void setSyncFinish(){
Log.i(TAG, "setSyncFinish to notify all");
synchronized (LOCK) {
SYNCING = false;
LOCK.notifyAll();
}
}
public class WaitingOnLoaderTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
Log.i(TAG, "doInBackground of WaitingForLoaderTask");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
waitForSync();
Log.i(TAG, "finishedWaiting!");
return null;
}
}
public class LoaderTask extends AsyncTask<Void, Void, Void>{
long mRuntime;
int mTimes;
public LoaderTask(long runtime, int times){
mRuntime = runtime;
mTimes = times;
}
@Override
protected Void doInBackground(Void... params) {
while(mTimes >= 0){
Log.i(TAG, "sleeping for " + mTimes + " times for " + mRuntime + " milliseconds");
mTimes--;
try {
Thread.sleep(mRuntime);
} catch (InterruptedException e) {
Log.e("MainActivity", "Interrupted", e);
}
}
setSyncFinish();
return null;
}
}
}
但我无法WaitingOnLoaderTask
正确等待。如果我在 onCreate 中运行它
new WaitingOnLoaderTask().execute((Void[])null);
new LoaderTask(1000, 5).execute((Void[])null);
我得到这样的 logOutput(发生死锁):
03-08 18:17:23.309: I/myUniqueLogTag(4432): setting Sync=true
03-08 18:17:23.317: I/myUniqueLogTag(4432): doInBackground of WaitingForLoaderTask
03-08 18:17:23.817: I/myUniqueLogTag(4432): waiting for Sync
和上
new LoaderTask(1000, 5).execute((Void[])null);
new WaitingOnLoaderTask().execute((Void[])null);
我得到这样的日志:
03-08 18:18:53.082: I/myUniqueLogTag(4621): sleeping for 5 times for 1000 milliseconds
03-08 18:18:54.082: I/myUniqueLogTag(4621): sleeping for 4 times for 1000 milliseconds
03-08 18:18:55.090: I/myUniqueLogTag(4621): sleeping for 3 times for 1000 milliseconds
03-08 18:18:56.082: I/myUniqueLogTag(4621): sleeping for 2 times for 1000 milliseconds
03-08 18:18:57.090: I/myUniqueLogTag(4621): sleeping for 1 times for 1000 milliseconds
03-08 18:18:58.106: I/myUniqueLogTag(4621): sleeping for 0 times for 1000 milliseconds
03-08 18:18:59.113: I/myUniqueLogTag(4621): doInBackground of WaitingForLoaderTask
03-08 18:18:59.113: I/myUniqueLogTag(4621): setSyncFinish to notify all
03-08 18:18:59.621: I/myUniqueLogTag(4621): waiting for Sync
03-08 18:18:59.621: I/myUniqueLogTag(4621): finishedWaiting!
所以我想一个是阻止另一个运行。他们是否doInBackground
实际上在同一个线程中计算它们,并LOCK.wait()
阻止该线程进一步执行?
有没有办法修复它(并保持与 Android 2.2 兼容)?
注意:第二个 Time 基本上是我想要的,但在其他 Task 实现中,我不能确定WaitingOnLoaderTask
只有在另一个完成时才执行。