【问题标题】:Why synchronized is necessary in getView, what if remove it?为什么getView需要同步,如果去掉呢?
【发布时间】:2013-11-19 07:54:04
【问题描述】:

我阅读了android源代码的ManageApplications.java并注意到这个'同步(条目)',我想知道这里是否有必要以及它如何'有效地绑定数据'?我认为更好地理解它可能会解决我的一些奇怪问题,提前谢谢你。

    public View getView(int position, View convertView, ViewGroup parent) {

        ...

        // ? Bind the data efficiently with the holder
        ApplicationsState.AppEntry entry = mEntries.get(position);
        synchronized (entry) {
            holder.entry = entry;
            if (entry.label != null) {
                holder.appName.setText(entry.label);
            }
        }
        mActive.remove(convertView);
        mActive.add(convertView);

        return convertView;
    }

【问题讨论】:

标签: android synchronized


【解决方案1】:

您正在从entryholder 中设置两个值。如果您不同步,则有可能在设置holder.entry 和调用holder.appName.setText() 之间运行另一个线程getView()。这会导致状态不佳。

【讨论】:

  • 感谢您的快速回复。但是我一直觉得getView()跟多线程没什么关系吧?
  • 在这种情况下,我不确定为什么会从两个线程调用 getView(),但代码的作者决定确保代码仍然正常工作。我冒昧地猜测,如果作者同步了这个方法,那么它是必要的。如果查看 (2.2.2_r1)[goo.gl/dz0Faf] 和 (2.3.1_r1)[goo.gl/mBxon6] 之间的代码,就会出现同步。
  • 非常感谢您的耐心等待。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
  • 2019-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-12
相关资源
最近更新 更多