在函数中通过类名同步是否在扩展类中有效?
我在基类中有一个方法 foo 使用 Synchronized (类名) ,以及扩展基类的两个类 A 和 B 。如果我在两个不同的线程中从 A 实例和 B 实例调用 foo,它们会同步吗?这是一个示例代码:
class BaseClass {
void foo() {
synchronized(BaseClass.class)
// do something like increment count
}
}
class A extends BaseClass {
}
class B extends BaseClass {
}
A a = new A();
B b = new B();
//in thread 1
a.foo() ;
//in thread 2
b.foo() ;
I have a methode foo in base class uses Synchronized (class name) , and two classes A and B that extends the base class. if i called foo from A instance and B instance in two different thread are they gonna be Synchronized. here's a sample code :
class BaseClass {
void foo() {
synchronized(BaseClass.class)
// do something like increment count
}
}
class A extends BaseClass {
}
class B extends BaseClass {
}
A a = new A();
B b = new B();
//in thread 1
a.foo() ;
//in thread 2
b.foo() ;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这将在扩展
BaseClass
的所有类(包括BaseClass
本身)的所有实例之间进行同步。BaseClass.class
引用基本上是整个类加载器的单个引用。你真的想要那个吗?通常,当需要同步时,静态方法应该在静态的东西上同步,实例方法应该在与实例相关的东西上同步。就我个人而言,我不喜欢在
this
或Class
引用上同步 - 因为这两个引用在其他地方都可用,因此其他代码可以在同一监视器上同步,从而使其成为可能很难推理同步。相反,我倾向于:(实际上我通常只使用
lock
作为名称;为了清楚起见,我只是在这里将其变得更加明确。)Yes, that will be synchronized across all instances of all classes extending
BaseClass
(includingBaseClass
itself). TheBaseClass.class
reference will basically be a single reference for the whole classloader. Do you really want that?Usually, when synchronization is required, static methods should synchronize on something static, and instance methods should synchronize on something related to the instance. Personally I don't like synchronizing on either
this
or aClass
reference - as both of those references are available elsewhere, so other code could synchronize on the same monitor, making it hard to reason about the synchronization. Instead, I would tend to have:(I typically actually just use
lock
as the name; I've just made it more explicit here for clarity.)是的,你们正在同步同一件事。
Yes, you are synchronizing on the same thing.
是的。它是同步的,尽管不能保证线程执行的顺序。
Yes. It is synchronized, even though sequence of thread execution is not guaranteed.