java.util.Observable 是线程安全的吗?
在java的观察者模式类Observer和Observable中,在不同的线程中调用Observable对象的notifyObservers(Object arg0),线程安全吗?
例子: 我有多个线程,所有Observables,它们都会经常调用notifyObservers(...)。所有这些线程都向单个观察者对象报告。
我会遇到并发问题吗?解决这个问题的更好方法是什么? 我知道使用事件侦听器的可能解决方案。但是我不确定如何实现它,而且如果可能的话,我想坚持使用观察者模式实现。
In java's Observer pattern classes Observer and Observable, are calls made to Observable objects's notifyObservers(Object arg0), in different threads, thread-safe?
Example:
I have multiple threads, all Observables, that will be calling notifyObservers(...) ever so often. All these threads report to a single Observer object.
Will I encounter concurrency issues, and what would be a better way to solve this?
I am aware of a possible solution using event listeners. However I am unsure how to implement it and also, I would like to stick with the Observer pattern implementation, if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从源代码(我有 Java 5 源代码,但 Java 6 和 7 应该是相同的)来看,您似乎只在
Observable
本身上进行了同步。来自
notifyObservers(...)
方法(在Observable
中):因此,如果
Observer
不更改任何共享数据,那么应该没问题。如果确实如此 - 您可能会使用不同的Observable
多次调用update(Observable, Object)
- 您需要自己在共享数据上添加同步。From the source code (I have Java 5 source, but it should be the same for Java 6 and 7) it seems like you only have synchronization on the
Observable
itself.From the
notifyObservers(...)
method (inObservable
):Thus if the
Observer
doesn't change any shared data it should be fine. If it does - you could have multiple calls toupdate(Observable, Object)
with differentObservable
s - you'd need to add synchronization on that shared data yourself.