在方法的本地范围内创建的ReentrantLock对象将如何工作? [英] How will ReentrantLock object created inside a method's local scope work?

查看:141
本文介绍了在方法的本地范围内创建的ReentrantLock对象将如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以上是OCP 7 java se书的屏幕打印.第791页.

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

我的问题是,是否每次在方法中创建一个新的ReentrantLock对象并将其锁定,如何阻止两个线程在lockunlock之间运行代码块?这两个线程不会分别创建一个ReentrantLock对象并将其锁定吗?我可以想象,如果lock对象是仅实例化一次且从未更改的实例变量,它将如何工作. (最好是final).

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).

我误会了吗?

我已经问过并且没有得到明确的答案.

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

推荐答案

您每次正确在方法本身中创建一个"ReentrantLock",以便同步该锁上的线程不起作用.必须有一个共享"锁对象.

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.

文档> 使用以下示例:

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

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

这篇关于在方法的本地范围内创建的ReentrantLock对象将如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆