简体   繁体   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;
}

But I'm not satisfied with the way I'm handling this. 但我对我处理这个问题的方式并不满意。 Is there a better way to do this? 有一个更好的方法吗?

You could use a CountDownLatch to wait for the other thread to complete. 您可以使用CountDownLatch等待其他线程完成。

http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/CountDownLatch.html http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/CountDownLatch.html

There are a multiple of possible solutions for this issue. 这个问题有多种可能的解决方案。 The most elegant way is as Eric mentioned above, CountDownLatch. 最优雅的方式是Eric上面提到的CountDownLatch。 Here is how you could proceed: 以下是您可以继续的方式:

// 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;
}

In SalesRequest.execute method, you could have the following: 在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

Also, make sure you are not calling getChildrenCount() from the UI thread otherwise your application will hang and will loose its responsiveness until you get an answer from the server. 此外,请确保您没有从UI线程调用getChildrenCount() ,否则您的应用程序将挂起并将失去其响应性,直到您从服务器获得答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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