本文介绍了Java:超类中的synchronized方法获取与子类中的锁相同的锁,对吧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A {
    public synchronized void myOneMethod() {
        // ...
    }
}

class B extends A {
    public synchronized void myOtherMethod() {
        // ...
    }
}

// ...

B myObject;

// ...

myObject.myOneMethod(); // acquires lock
myObject.myOtherMethod(); // same lock?

我如何理解同步模型,我会说是的,它是,因为锁/监视器与实例myObject相关联,并且在何处定义方法也无关紧要。但是我是对的吗?如果不是,为什么?如果是,为什么你肯定,我不是? : - )

How I understand the synchronization model, I'd say that yes, it does, because the lock / monitor is associated with the instance myObject, and it doesn't matter where the method was defined. But am I right? If not, why? If yes, why are you sure, and I'm not? :-)

推荐答案

是的,你是对的,你也有解释。

Yes, you are right, and you got the explanation right too. Nothing much to add.

请注意,如果方法是 static ,那么它们将在不同的对象上同步,即它们各自的类B)。

Note that if the methods were static, then they would synchronize on different objects, namely their respective classes (A and B).

编辑:为什么?我不知道,你为什么不确定? ;-) myObject 只是一个对象 - 来自类A的 myObject 属性没有任何区别和那些来自B类(嗯,技术上你可以使用反射找出哪些是哪些,所以必须有一些区别,但忘记现在的反射对于常见的操作对象没有区别。)

EDIT: Why am I sure? I don't know, why are you not sure? ;-) myObject is just one object - there isn't any distinction between the myObject attributes that come from class A and those that come from class B. (Well, technically you could probably use reflection to find out which are which, so there must be some distinction, but forget about reflection for now. For common operations on the object there's no distinction.)

这篇关于Java:超类中的synchronized方法获取与子类中的锁相同的锁,对吧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 23:47