本文介绍了Java 中可重入锁中的 synchronized(object) 的等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面给出的代码中.如何知道 Reentrant Lock 锁定了哪个对象?

In the code given below. How can I know which object Reentrant Lock has locked ?

Public class Test {

    Map obj1 = new HashMap();
    Object ob2 = new Object();

    void Method() {

        //First
        synchronized(ob1) { // Locks obj1

        }
        synchronized(ob2) { // Locks obj2

        }

        //Second
        Lock lock = new ReentrantLock(); // Which object is getting locked here?
        lock.lock();
        try {

        } finally {
            lock.unlock();
        }

    }

}


在上面的例子中,哪个对象被锁定了?如果我想使用可重入锁显式锁定 obj1 和 obj2 怎么可能?

In the above example which Object is getting locked ? If I want to explicitly lock obj1 and obj2 using Reentrant lock how is it possible ?

推荐答案

Lock lock = new ReentrantLock(); // Which object is getting locked here?
lock.lock();

lock 对象被锁定在那里.

我想你可能误解了 synchronized(ob1) {...} 的作用.它不会阻止其他线程使用obj1.它唯一阻止的是,它阻止其他线程同时在同一个对象上同步.

I think maybe you misunderstand what synchronized(ob1) {...} does. It does not prevent other threads from using obj1. The only thing it prevents is, it prevents other threads from being synchronized on the same object at the same time.

Java(以及大多数其他编程语言/库)中的锁被称为咨询锁.咨询"意味着,程序员必须知道锁应该保护哪些数据,并且程序员有责任确保程序中的任何线程都不会使用该数据,除非线程锁定了锁.

Locks in Java (and in most other programming languages/libraries) are so-called advisory locks. "Advisory" means, the programmer has to know what data are supposed to be protected by the lock, and the programmer is responsible for ensuring that no thread in the program ever uses that data except when the thread has locked the lock.

仅供参考:干净"Java中的做法是这样使用synchronized:

FYI: A "clean" practice in Java is to use synchronized in this way:

class MyClass {

    private final Object lock = new Object();
    private TypeA sharedMemberVariable_a;
    private TypeB sharedMemberVariable_b;
    ...

    public SomeType someMethod() {
        ...
        synchronized(lock) {
            ...access shared member variables...
        }
        return ...;
    }
}

此模式允许您发布 MyClass 的实例,而无需将 lock 对象暴露给调用者.它还非常清楚地区分了 lock 对象本身和受锁保护的数据/关系.

This pattern allows you to publish instances of MyClass without exposing the lock object to callers. It also makes very clear the distinction between the lock object itself, and the data/relationships that are protected by the lock.

如果将来需要,该模式还可以使从使用 synchronized 切换到使用 Lock 对象变得非常容易.

The pattern also makes it trivially easy to switch from using synchronized to using a Lock object if you need to do so in the future.

这篇关于Java 中可重入锁中的 synchronized(object) 的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-16 08:34