Java 学习笔记之 Synchronized锁重入

Synchronized锁重入:

 

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

public class SyncReUseService {
    synchronized public void service1(){
        System.out.println("service1");
        service2();
    }

    synchronized public void service2(){
        System.out.println("service2");
        service3();
    }

    synchronized public void service3(){
        System.out.println("service3");
    }
}

public class SyncReUseServiceThread extends Thread {
    @Override
    public void run() {
        super.run();
        SyncReUseService service = new SyncReUseService();
        service.service1();
    }
}

public class ThreadRunMain {
    public static void main(String[] args) {
        testSyncReUseServiceThread();
    }

    public static void testSyncReUseServiceThread(){
        SyncReUseServiceThread t = new SyncReUseServiceThread();
        t.start();
    }
}

运行结果:

《Java 学习笔记之 Synchronized锁重入》

 

当存在父子继承关系时,子类也可以通过“可重入锁”调用父类的同步方法。

public class FatherClass {
    public int i = 10;
    synchronized public void operateIMainMethod(){
        try {
            i--;
            System.out.println("Father class print i = " + i);
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

public class SunClass extends FatherClass {
    synchronized public void operateISubMethod(){
        try {
            while (i > 0) {
                i--;
                System.out.println("Sun class print i = " + i);
                Thread.sleep(100);
                this.operateIMainMethod();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class FatherSunThread extends Thread {
    @Override
    public void run() {
        super.run();
        SunClass sub = new SunClass();
        sub.operateISubMethod();
    }
}

public class ThreadRunMain {
    public static void main(String[] args) {
        testFatherSunThread();
    }

    public static void testFatherSunThread(){
        FatherSunThread t = new FatherSunThread();
        t.start();
    }
}

运行结果:

《Java 学习笔记之 Synchronized锁重入》

 

    原文作者:AK47Sonic
    原文地址: https://www.cnblogs.com/AK47Sonic/p/7721727.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞