Java锁和发生前关系

发布于 2024-12-12 10:50:20 字数 223 浏览 2 评论 0原文

我不确定我是否正确解释了 javadoc。在调用 lock 方法并成功获得锁后使用 ReentrantLock 时,您是否可以在没有任何同步块的情况下访问任何对象,并且发生之前的关系会神奇地强制执行?

我没有看到 ReentrantLock 和我正在处理的对象之间有任何联系,这就是为什么很难相信我可以安全地处理它们。但事实就是如此,还是我读的javadoc错了?

I'm not sure if I'm interpreting the javadoc right. When using a ReentrantLock after calling the lock method and successfully gaining a lock, can you just access any object without any synchronized blocks and the happend-before relationship is magically enforced?

I don't see any connection between the ReentrantLock and the objects I'm working on, that's why it is hard to believe I can work on them safely. But this is the case, or am I reading the javadoc wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱情眠于流年 2024-12-19 10:50:20

如果线程 A 修改了由锁保护的代码块 CB1 内的某个对象,然后释放锁,并且线程 B 进入由同一锁保护的代码块中,则线程 B 将在代码中看到线程 A 所做的修改块 CB1。

如果两个线程读取和写入相同的共享状态,则对该状态的每次读取和写入都应该由相同的锁来保护。

If thread A has modified some object inside a code block CB1 guarded by the lock and then releases the lock, and thread B enters in a code block guarded by the same lock, then thread B will see the modifications done by thread A in the code block CB1.

If two threads read and write the same shared state, then every read and write to this state should be guarded by the same lock.

牵你手 2024-12-19 10:50:20

它是......(互斥)锁:

void myMethod()
{

    myLock.lock();  // block until condition holds
    try 
    {
         // Do stuff that only one thread at a time should do
     } 
     finally 
     {
         myLock.unlock()
     }
}

一次只有一个线程可以持有锁,因此 lock()unlock() 调用之间的任何操作都保证一次只能由一个线程执行。

可以在此处找到相关的 Oracle 教程。

It's ... a (mutex) lock:

void myMethod()
{

    myLock.lock();  // block until condition holds
    try 
    {
         // Do stuff that only one thread at a time should do
     } 
     finally 
     {
         myLock.unlock()
     }
}

Only one thread can hold the lock at a time, so anything between the lock() and unlock() calls is guaranteed to only be executed by one thread at a time.

The relevant Oracle tutorial can be found here.

橪书 2024-12-19 10:50:20

这里面没有魔法。当且仅当访问某个对象的所有线程都使用相同的锁时(无论是 ReentrantLock 还是任何其他互斥锁,例如 Synchronized 块),您才是安全的。

ReentrantLock 的存在是合理的,因为它比 synchronized 提供了更多的灵活性:例如,您可以尝试获取锁 - 不可能与同步

There's no magic in it. You're safe if, and only if, all threads accessing an object use the same lock - be it a ReentrantLock or any other mutex, such as a synchronized block.

The existence ReentrantLock is justified by that it provides more flexibility than synchronized: you can, for example, just try to acquire the lock - not possible with synchronized.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文