2015-10-15 66 views
-1

爲什麼下面的代碼不是死鎖並且工作正常?java基本多線程

public class Concurrent { 

    public static void main(String[] args) { 
     Concurrent my = new Concurrent(); 
     my.method1(); 

    } 

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

    private synchronized void method2() { 
     System.out.println("method2"); 
    } 
} 

Output: 
method1 
method2 

當我調用method1()監視器被鎖定。 JVM或編譯器無法調用method2(),因爲此方法也通過監視「my」對象進行同步。但它工作正常。

回答

5

爲什麼問題中的代碼不會死鎖?

由於原始互斥量(監視器)是可重入的。當給定互斥體中的線程嘗試再次獲取它時,它不會阻塞。

JLS 17.1

「A線程t可能會鎖定特定的監視器多次;每個解鎖反轉一個鎖定操作的效果」。

+0

感謝您的解釋,我認爲如果我需要一個可重入的鎖,我應該使用java.util.concurrent.locks.ReentrantLock。此外,我認爲我的問題中的代碼是死鎖,但jvm或編譯器「優化」我的代碼以防止死鎖。 –