有对这个问题的可能解决方案的倍数。最优雅的方式就像Eric上面提到的CountDownLatch。 这里是你如何才能够着手:
// Lock to signal Children are created
CountDownLatch childrenReady = new CountDownLatch(1/*wait for one signal*/);
public int getChildrenCount(int groupPosition) {
if(children == null){
SalesRequest request = new SalesRequest(childrenReady /*pass on this lock to worker thread*/);
request().execute(); // runs in other thread which
// initialises children with some value.
childrenReady.await(); // Wait until salesRequest finishes
while(children == null){
// I'm doin this to avoid null pointer Exception.
// So it comes out of the loop only when childern
// gets initialised.
}
}
return children.length;
}
在SalesRequest.execute方法,你可以有以下几点:
// Populate and create children structure of the calling object
// When done, signal to callee that we have finished creating children
childrenReady.countDown(); // This will release the calling thread into the while loop
此外,还要确保你没有从UI线程,否则你的应用程序中调用getChildrenCount()
将会挂起并且将放弃其响应,直到您从服务器获得答案。
向下选民plz添加评论..我可以改变这个问题,如果我不清楚..我只是寻求一些帮助.. – ngesh
我不是downvoter,但你能解释你想要什么实现上面的代码? – zengr
@zengr ..它实际上是android代码..我需要根据服务器响应更新UI。自从它回调后,我无法控制该方法。所以我有覆盖它来初始化一些变量。 – ngesh