synchronized:内置锁重入(一)

示例描述

在继承的前提下,子类“重写”父类synchronized方法使用的对象锁,和父类synchronized方法是否是同一个对象?答案是:肯定的。

解析

内置锁的归属者是实例,不是某一个类。运行期间的实例是确认唯一的,所以锁对象也是相同的。

代码示例:

package com.bicai.lock;

/**
 * @Author lizhengjun
 * @Date 2020/6/28
 * @Desc 父类:动物
 */

public class Animal {

    public synchronized void eat() {
        System.out.println("Animal: eat....");
    }
}
package com.bicai.lock;

/**
 * @Author lizhengjun
 * @Date 2020/6/28
 * @Desc 子类:小狗
 */

public class Dog extends Animal {

    @Override
    public synchronized void eat() {
        System.out.println("Animal: eat....");
        System.out.println("Dog: eat.... supuer锁:" + super.toString());
        System.out.println("Dog: eat.... this锁:" + this);
    }
}

测试:

    public static void main(String[] args) {
        Animal animal = new Dog();
        animal.eat();
    }

输出结果:

Animal: eat....
Dog: eat.... supuer锁:com.bicai.lock.Dog@4554617c
Dog: eat.... this锁:com.bicai.lock.Dog@4554617c

猜你喜欢

转载自www.cnblogs.com/qiancdd/p/13201732.html