问题描述
以上是OCP 7 java se书的屏幕打印.第791页.
The above is a screen print from OCP 7 java se book. page 791.
我的问题是,是否每次在方法中创建一个新的ReentrantLock
对象并将其锁定,如何阻止两个线程在lock
和unlock
之间运行代码块?这两个线程不会分别创建一个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对象将如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!