synchronized锁的重入问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xyc_csdn/article/details/78161288

  我们知道通过synchronized关键字修饰的方法或代码块在同一时刻只能被一个线程访问,还有一种就是锁的重入问题,就是一个线程可以访问多个被synchronized修饰的方法或代码块,代码如下:

  • 代码
package com.xiayc.sync;

public class ReentrantSynchronized {

    public class Super{
        public synchronized void SuperMethod() {
            System.out.println("hello SuperMethod");
        }
    }

    public class Sub extends Super{
        public synchronized void SubMethod1() {
            this.SubMethod2();
        }

        public synchronized void SubMethod2() {
            this.SuperMethod();
        }
    }


    public static void main(String[] args) {
        ReentrantSynchronized reentrantSynchronized = new ReentrantSynchronized();
        ReentrantSynchronized.Sub sub = reentrantSynchronized.new Sub();
        sub.SubMethod1();
    }
}
  • 执行结果
hello SuperMethod

向上述代码的调用方式,尽管是不同的synchronized方法,但可以做到一个线程的同时调用。

猜你喜欢

转载自blog.csdn.net/xyc_csdn/article/details/78161288