java - 我如何避免这种忙等待?

标签 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;
}

但我对自己处理此事的方式不满意。有更好的方法吗?

最佳答案

您可以使用 CountDownLatch 来等待其他线程完成。

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

关于java - 我如何避免这种忙等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8207905/

相关文章:

java - GSON toJson() 方法为 POJO 返回 null

android - 如何在我的应用及其库中仅实例化一次Singleton?

java - SwingUtilities.invokeLater 做什么?

Android RegEx 找不到匹配项

c++ - 如何将以下线程模型从 C++ 转换为 go?

java - 发送大量 POST 请求

java - PriorityQueue 的顺序不符合预期

java - 在没有可用源代码的情况下编译 GWT 项目

java - ListView 中的按钮不可点击

android - 请求应用程序更新许可