Mixing synchronized() with ReentrantLock.lock()

前端 未结 3 1210
情话喂你
情话喂你 2021-02-05 12:37

In Java, do ReentrantLock.lock() and ReetrantLock.unlock() use the same locking mechanism as synchronized()?

My guess is \"No,\" b

3条回答
  •  灰色年华
    2021-02-05 12:50

    No, Thread 2 can lock() even when Thread 1 is synchronized on the same lock. This is what the documentation has to say:

    Note that Lock instances are just normal objects and can themselves be used as the target in a synchronized statement. Acquiring the monitor lock of a Lock instance has no specified relationship with invoking any of the lock() methods of that instance. It is recommended that to avoid confusion you never use Lock instances in this way, except within their own implementation.

提交回复
热议问题