synchronized重入后拋出異常,鎖釋放了嗎


synchronized:

用於同步方法或者代碼塊,使得多個線程在試圖並發執行同一個代碼塊的時候,串行地執行。以達到線程安全的目的。

允許重入:

在多線程的時候是這樣的,但是對於單線程,是允許重入的,每重入一次,計數器加1,當退出代碼塊時,計數器減1。

兩次重入,在內層拋出異常:

那正常退出時計數器減1,拋異常時計數器也是減1。那如果兩次重入,在內層拋出異常,會釋放鎖嗎?還是只會計數器減1,鎖並不會釋放?

直接上代碼驗證:

public class SynchronizedTest1 {
    public static void main(String[] args){
        Test test1 = new Test();
        Thread thread1 = new Thread(test1);
        Thread thread2 = new Thread(test1);
        thread1.start();
        thread2.start();
    }
}
class Test implements Runnable{
    public synchronized void hello() throws Exception{
        System.out.println(Thread.currentThread().getName() + " say hello!!");
        sorry();
        System.out.println(Thread.currentThread().getName() + " helloed");
    }
    public synchronized void sorry() throws Exception{
        System.out.println(Thread.currentThread().getName() + " say sorry!!");
        throw new Exception(Thread.currentThread().getName() + " this is a test!");
    }
    public void run() {
        try {
            hello();
        }catch (Exception e){
            System.out.println(Thread.currentThread().getName() + " exception once");
        }
        try {
            Thread.sleep(10000L);
            System.out.println(Thread.currentThread().getName() + " exit");
        }catch (Exception e){
            System.out.println(Thread.currentThread().getName() + " some exception");
        }
    }
}
Thread-0 say hello!!
Thread-0 say sorry!!
Thread-0 exception once
Thread-1 say hello!!
Thread-1 say sorry!!
Thread-1 exception once
Thread-1 exit
Thread-0 exit

Process finished with exit code 0

  

從以上運行結果,得出以下結論:

synchronized重入之后,內層拋出異常,跳出synchronized代碼塊,會釋放鎖。

題外話:一個很無聊的論點,結果顯而易見,重點是有疑問時,寫代碼論證消除疑慮是最直接的方式。


免責聲明!

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



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