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();
    }
}

運行結果:

 

當存在父子繼承關系時,子類也可以通過“可重入鎖”調用父類的同步方法。

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();
    }
}

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM