在java.util.concurrent.Locks中使用API时,究竟锁定了什么? [英] What exactly gets locked when using APIs in java.util.concurrent.Locks?
问题描述
这可能是一个非常愚蠢的问题.我正在阅读包java.util.concurrent.atomic
和java.util.concurrent.locks
中的接口和类的文档.我到处都可以找到
This is probably a very silly question. I am reading through the documentation of interfaces and classes in packages java.util.concurrent.atomic
and java.util.concurrent.locks
. I find everywhere that
void lock()–获取锁(如果有);如果没有可用的锁,则在释放锁之前线程将被阻塞
void lock() – acquire the lock if it’s available; if the lock isn’t available a thread gets blocked until the lock is released
我不确定的是,到底什么资源被锁定?代码段示例显示
What I am not sure about is, what resource is exactly getting locked? The code snippet examples show
Lock lock = new ReentrantLock();
lock.lock();
try {
// access to the shared resource
} finally {
lock.unlock();
}
在lock()
调用下使用的所有内容是否都被锁定? JVM如何知道这一点?如果lock()
和unlock()
之间有多个资源怎么办?我想我有这个问题,因为我在阅读synchronization
之后就读了此书,并且它具有非常具体的方式来表示要锁定的内容-如:synchronized(resourceReferenceThatNeedsToBeLocked)
Does whatever that is used under the call of lock()
get locked? How does JVM know that before getting to that line? And what if there are multiple resources between lock()
and unlock()
? I guess I am having this question because I am reading this right after reading synchronization
and it has very specific way of saying what to lock - like: synchronized(resourceReferenceThatNeedsToBeLocked)
我进行了大量研究,但找不到该问题的答案.
I reseached a lot and yet can't find answer for this question.
推荐答案
回答我的问题:
被锁定的对象是引用变量lock
所引用的对象.在这种情况下,是ReentrantLock
对象.
The object that is locked is the object that reference variable lock
is referring to. In this case a ReentrantLock
object.
要注意的重要事项:
上面的代码可能会引起误导.在方法中创建新的lock
对象将由相应的线程完成,并且相应的线程将仅锁定在其堆栈中创建的对象.如果要锁定特定实例的变量或方法,则该实例应具有其自己的lock
对象,并且仅应使用同一锁定对象进行同步.
The code above is potentially misguiding. Creating a new lock
object in a method would be done by respective threads, and the respective thread will only lock that was created in it's stack. If you want to lock a particular instance's variables or methods, that instance should have its own lock
object and only that same lock object should be used for synchronisation.
Refer this question for more info. Refer this documentation of the lock in question.
这篇关于在java.util.concurrent.Locks中使用API时,究竟锁定了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!