我想启动2个异步任务,但只有一个被执行。logcat的输出应该类似于:
firstAsync started
secondAsync started
secondAsync ends
firstAsync ends
end
但是logcat的输出是
firstAsync started
end
它表明第二个异步从未执行过。
下面是Java代码:
package com.example.async;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
public class MainActivity extends Activity {
public boolean stopAsync=false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new firstAsync().execute();
new secondAsync().execute();
Log.e("end","end");
}
class firstAsync extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
Log.e("firstAsync started","firstAsync started");
while(!stopAsync)
{
}
Log.e("firstAsync ends","firstAsync ends");
return null;
}
}
class secondAsync extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
Log.e("secondAsync started","secondAsync started");
stopAsync = true;
Log.e("secondAsync ends","secondAsync ends");
return null;
}
}
}
所以,问题是,我如何启动多个异步任务,希望你能帮助我。
当做
克里斯
最佳答案
AsyncTask
总是一次执行一个,除非您使用executeOnExecutor()
:
asynctask被设计为Thread
和Handler
周围的帮助类,不构成通用线程框架。
从HONEYCOMB
开始,任务在单个线程上执行
避免由并行执行引起的常见应用程序错误。如果你
真正想要并行执行,您可以调用executeOnExecutor(java.util.concurrent.Executor, Object[])
THREAD_POOL_EXECUTOR