可重入同步——被调用同步方法的解锁

Reentrant Synchronization- Unlocking of called synchronized method

void method1() {
     synchronized(this) {  // Acquires intrinsic lock
      method2();
    }   
}

void method2() {
     synchronized(this) {} // Acquires same lock due to Reentrant synchronization
}

第一次在方法 1 中获取锁,它调用同步方法 2,第二次获取相同的锁。

现在我的疑问是,当同步块在 method2() 中结束时,解锁是否第一次发生在这里,returns 到 method1() 的同步块,第二次解锁再次发生。

它是否像 ReentrantLock 一样在内部管理锁的数量?

是在内部 jdk 跟踪重新进入。

根据 oracle 文档:

Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.

详情见this

Does it internally manages count of locks like in ReentrantLock ?

是的。来自 JLS section 17.1 - 强调我的。

The Java programming language provides multiple mechanisms for communicating between threads. The most basic of these methods is synchronization, which is implemented using monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. A thread t may lock a particular monitor multiple times; each unlock reverses the effect of one lock operation.