gpt4 book ai didi

java - 为什么 Observable 类中的方法是同步的?

转载 作者:行者123 更新时间:2023-12-02 09:51:39 54 4
gpt4 key购买 nike

为什么Observable类中的方法是同步的?

public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
}

最佳答案

Observable 旨在成为一个非常线程安全的类;它以“原子方式”操作共享数据,这意味着一次只有一个线程可以访问它。 synchronized 关键字强制每个交互线程以原子方式访问 Observable 实例的数据。

synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.

请注意,某些方法(例如 notifyObservers())不是同步。这是因为它们不会直接影响 Observable 的实例数据。

阅读this writeup如果您想了解有关线程安全的更多信息。

关于java - 为什么 Observable 类中的方法是同步的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56280774/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com