繁体   English   中英

我该如何避免这种忙碌的等待?

[英]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;
}

但我对我处理这个问题的方式并不满意。 有一个更好的方法吗?

这个问题有多种可能的解决方案。 最优雅的方式是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM