2011-11-21 59 views
3
public int getChildrenCount(int groupPosition) { 
    if(children == null){ 
     new SalesRequest().execute(); // runs in other thread which 
             // initialises children with some value. 
     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; 
} 

但我不满意我处理这个问题的方式。有一个更好的方法吗?如何避免这种忙碌的等待?

+2

向下选民plz添加评论..我可以改变这个问题,如果我不清楚..我只是寻求一些帮助.. – ngesh

+0

我不是downvoter,但你能解释你想要什么实现上面的代码? – zengr

+0

@zengr ..它实际上是android代码..我需要根据服务器响应更新UI。自从它回调后,我无法控制该方法。所以我有覆盖它来初始化一些变量。 – ngesh

回答

3

有对这个问题的可能解决方案的倍数。最优雅的方式就像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()将会挂起并且将放弃其响应,直到您从服务器获得答案。