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

时间:2011-11-21 06:06:14

标签: java android multithreading

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 个答案:

答案 0 :(得分:5)

答案 1 :(得分: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(),否则您的应用程序将挂起并且在您从服务器获得答案之前将失去其响应性。