How will ReentrantLock object created inside a method's local scope work?

半腔热情 提交于 2019-12-11 01:51:58

问题


The above is a screen print from OCP 7 java se book. page 791.

My question is if a new ReentrantLock object is created in a method every time and locked, how would that stop two threads from running the code block in between lock and unlock? Won't the two threads create a ReentrantLock object each and lock it? I can imagine how this would work if lock object was a instance variable only instantiated once and never changed. (preferrably final).

Am I misunderstanding something?

I had already asked this and Did not get a clear answer.


回答1:


You are right creating a 'ReentrantLock' in the method itself each and every time in order to synchronise Threads on that lock does not work. There has to be a "shared" lock object.

The example in the book is maybe a bit too simplistic.

The documentation of ReentrantLock uses the following example:

class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
 }


来源:https://stackoverflow.com/questions/55294843/how-will-reentrantlock-object-created-inside-a-methods-local-scope-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!