2011-11-21 128 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()將會掛起並且將放棄其響應,直到您從服務器獲得答案。