我创建了一个类DataAdapter
,它启动线程以从webservices获取数据。使用
DataAdapter.InitData();
我怎么知道两个线程何时完成?
由于 七月
public class DataAdapter {
private final static String URL = "http://www.mywebservice.com";
private final static String URL_AD = "http://www.mywebservice2.com";
public void InitData(){
new GetInitData().execute(URL);
new GetAd().execute(URL_AD);
}
private static class GetInitData extends AsyncTask<String, Integer, JSONObject> {
protected JSONObject doInBackground(String... urls) {
JSONObject json = RestJsonClient.getJSONObject(urls[0]);
return json;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(JSONObject json) {
//process data
}
}
private static class GetAd extends AsyncTask<String, Integer, JSONObject> {
protected JSONObject doInBackground(String... urls) {
JSONObject json = RestJsonClient.getJSONObject(urls[0]);
return json;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(JSONObject json) {
//process data
}
}
}
答案 0 :(得分:0)
使用此:
public class DataAdapter {
private final String URL = "http://www.mywebservice.com";
private final String URL_AD = "http://www.mywebservice2.com";
private boolean finished = false;
public void InitData(){
new GetInitData(this).execute(URL);
new GetAd(this).execute(URL_AD);
}
public void finished(){
if(!finished){
finished = true;
}else{
Log.d("TAG","Both have finished"):
}
private class GetInitData extends AsyncTask<String, Integer, JSONObject> {
Activity ac = null;
public GetInitData(Activity ac){
this.ac=ac;
}
protected JSONObject doInBackground(String... urls) {
JSONObject json = RestJsonClient.getJSONObject(urls[0]);
return json;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(JSONObject json) {
//process data
ac.finished();
}
}
private class GetAd extends AsyncTask<String, Integer, JSONObject> {
Activity ac = null;
public GetInitData(Activity ac){
this.ac=ac;
}
protected JSONObject doInBackground(String... urls) {
JSONObject json = RestJsonClient.getJSONObject(urls[0]);
return json;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(JSONObject json) {
//process data
ac.finished();
}
}
}
答案 1 :(得分:0)
向DataAdapter类添加一个synchronized方法,其中每个AsyncTask都在其onPostExecute()中运行。在此方法中,您设置一个布尔变量,指示第一个作业完成,当第二个AsyncTask调用该方法时,它检查第一个线程是否已经完成。如果两者都已完成,您可以使用自定义代码。