What is the meaning of “ReentrantLock” in Java?

后端 未结 6 1952
故里飘歌
故里飘歌 2020-11-30 22:18

Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis.

Since an intrinsic lock is held by a thread, doesn\'t it mean that a threa

6条回答
  •  [愿得一人]
    2020-11-30 22:25

    This just means once a thread has a lock it may enter the locked section of code as many times as it needs to. So if you have a synchronized section of code such as a method, only the thread which attained the lock can call that method, but can call that method as many times as it wants, including any other code held by the same lock. This is important if you have one method that calls another method, and both are synchronized by the same lock. If this wasn't the case the. The second method call would block. It would also apply to recursive method calls.

    public void methodA()
    {
         // other code
         synchronized(this)
         {
              methodB();
         } 
    }
    
    public void methodB()
    {
         // other code
         syncrhonized(this)
         {
              // it can still enter this code    
         }
    
    }
    

提交回复
热议问题