【Java多线程】synchronized-锁重入

1.什么是锁重入?

在使用synchronized时,当一个线程得到一个对象锁后,再次请求此对象锁时是可以再次得到该对象的锁的。这也证明在一个synchronizes方法/块的内部调用本类的其他synchronized方法/块时,也是 永远可以得到锁的。

public class SyncDubbo1 {

    public synchronized void method1() {
        System.out.println("method1..");
        method2();
    }
    public synchronized void method2() {
        System.out.println("method2..");
        method3();
    }
    public synchronized void method3() {
        System.out.println("method3..");
    }

    public static void main(String[] args) {
        final SyncDubbo1 sd = new SyncDubbo1();
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                sd.method1();

            }
        });
        t1.start();
    }
}

这里写图片描述

2.什么是可重入锁?
自己可以再次获得自己的内部锁。比如有一条线程获得了某个对象的锁,此时这个对象锁还没有释放,当其再次想要获得这个对象的锁的时候还是可以获取的,如果不可重入锁的话,就会造成死锁。

static class Main{
        public int i =10;
         public synchronized void operationSup() {
             try {
                i--;
                System.out.println("Main print i=" + i);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
         }
    }

    static class Sub extends Main{
        public synchronized void operationSub() {
            try {
                while(i > 0) {
                    i--;
                    System.out.println("Sub print i = " + i);
                    Thread.sleep(1000);
                    this.operationSup();
                }
            } 
                catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                Sub sub = new Sub();
                sub.operationSub();

            }
        });
        t1.start();
    }

这里写图片描述

当子类线程暂停1s,父类方法被调用,当父类线程暂停1s,子类方法被调用,这证明,子类可以通过“可重入锁”调用父类的同步方法

猜你喜欢

转载自blog.csdn.net/zjy15203167987/article/details/80558515