[英]How do I avoid this busy-wait?
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;
}
但我對我處理這個問題的方式並不滿意。 有一個更好的方法嗎?
您可以使用CountDownLatch等待其他線程完成。
http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/CountDownLatch.html
這個問題有多種可能的解決方案。 最優雅的方式是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()
,否則您的應用程序將掛起並將失去其響應性,直到您從服務器獲得答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.