Synchronising twice on the same object?

前端 未结 6 592
生来不讨喜
生来不讨喜 2020-12-13 01:45

I was wondering if in Java I would get any odd behaviour if I synchronise twice on the same object?

The scenario is as follows

pulbic class SillyClas         


        
6条回答
  •  -上瘾入骨i
    2020-12-13 02:08

    Reentrant

    Synchronized blocks use reentrant locks, which means if the thread already holds the lock, it can re-aquire it without problems. Therefore your code will work as you expect.

    See the bottom of the Java Tutorial page Intrinsic Locks and Synchronization.

    To quote as of 2015-01…

    Reentrant Synchronization

    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.

提交回复
热议问题