我正在使用countdownlatch,如下例所示。在这里BackgroundDataPopulator创建一个AyncTask,该AyncTask依次调用PackagePopulator中的displayData。但是它永远不会发生,并且活动会卡住。我在这里做错了。
public class PackagePopulator implements ServerDataProcessor {
private CountDownLatch counter=new CountDownLatch(1);
String[] packages;
public void getPagesFromServer() {
new BackgroundDataPopulator(IMgrApplication.getAppContext().getString(R.string.list),new PData(),this).execute();
}
public String[] getPages() {
try {
counter.await();
} catch (InterruptedException e) {
packages=new String[0];
}
return packages;
}
@Override
public void displayData(ServerOutput output) {
Page[] pgArray = new Page[((PageData)output).getPages().size()];
pages=new String[pgArray.length];
pgArray = ((PageData)output).getPages().toArray(pgArray);
for(int i=0;i<pgArray.length;i++){
pages[i]=pgArray[i].getName();
}
counter.countDown();
}
}
public class BackgroundDataPopulator extends AsyncTask<Void, String, ServerOutput> {
// connector=new JSONConnector();
Connector connector;
String curUrl;
ServerOutput curServerOutput;
ServerDataProcessor processor;
public BackgroundDataPopulator(String url, ServerOutput serverOutput,ServerDataProcessor curProcessor) {
//connector = new UnitTestConnector();
connector = new JSONConnector();
curUrl = url;
curServerOutput = serverOutput;
processor=curProcessor;
}
@Override
protected ServerOutput doInBackground(Void... params) {
return connector.getData(URLUtils.getFormattedUrl(curUrl),curServerOutput);
}
@Override
protected void onPostExecute(ServerOutput output) {
processor.displayData(output);
//Toast.makeText(BaseFragmentActivity.this, "Done!",Toast.LENGTH_SHORT).show();
}
}
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
pagePopulator=new PagePopulator();
pagePopulator.getPagesFromServer();
super.onCreate(savedInstanceState);
}
public ArrayAdapter<CharSequence> getSpinnerDataArray(String item) {
return new ArrayAdapter<CharSequence>(this,android.R.layout.simple_spinner_item,pagePopulator.getPages());
}
最佳答案
目前尚不清楚您到底在做什么以及在哪里启动AscynTask。似乎您在同一线程上调用await()
和countDown()
,这就是为什么您被阻止的原因。发布更多详细信息和/或调试您的代码。
关于android - android中的CountDownLatch问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10678882/