为什么隐式锁不会发生死锁?

Why deadlock is not happening for implicit locks?

What is the Re-entrant lock and concept in general?

If a lock is non re-entrant you could grab the lock, then block when you go to grab it again, effectively deadlocking your own process.

public class ImplicitLock {

synchronized public void test1() {
    System.out.println("enter test1");
    test2();
    System.out.println("exit test1");

}

synchronized public void test2() {
    System.out.println("inside test2");

}

}

从 main class 开始,我执行了

ImplicitLock lock1 = new ImplicitLock();
lock1.test1();

我得到了以下输出,虽然我期望在调用 test2 时出现死锁,但它没有

enter test1
inside test2
exit test1

Java 同步锁是可重入的。 来自 Jakob Jenkov 博客:

锁定重入

Java 中的同步块是可重入的。这意味着,如果 Java 线程进入一个同步代码块,并因此锁定该块同步的监视器对象,该线程可以进入同步的其他 Java 代码块监控对象。这是一个例子:

public class Reentrant{
    public synchronized outer(){
        inner();
    }
    public synchronized inner(){
        //do something
    }
}

取自:http://tutorials.jenkov.com/java-concurrency/locks.html

可以说隐式锁是可重入的。所以基本上如果你尝试在同一个线程中锁定它两次你可以因为这个线程已经拥有那个锁。

看这里http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html

"A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements..."