简体   繁体   English

我可以访问Java中同步块使用的锁吗?

[英]Can I access the Lock used by a synchronized block in Java?

Having a simple List: 有一个简单的列表:

private final List<Item> lst = new ArrayList();

When I need synchronization, I used to do the following: 当我需要同步时,我曾经做以下事情:

synchronized (lst) {
    // Some code
}

Now, I need to create a Condition object using Lock.newCondition() , can I access the underlying lock used by synchronized{} to use it to create my condition, or should I remove synchronized blocks and use a custom Lock object ? 现在,我需要使用Lock.newCondition()创建一个Condition对象,是否可以访问Lock.newCondition() synchronized{}使用的基础锁来使用它创建条件,还是应该删除同步块并使用自定义Lock对象?

If you need a Condition object, is a clear sign that intrinsic locking are not enough for you. 如果您需要一个Condition对象,则明确表明内部锁定不足以满足您的需求。 You will need to use 您将需要使用

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

Anyway, if you are worried about performances, that is not a problem with modern virtual machines. 无论如何,如果您担心性能,那么对于现代虚拟机来说这不是问题。 Explicit locking perform as well as intrinsic one. 显式锁定与固有锁定一样好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我不能直接访问(并锁定)对象用于同步块的隐式锁 - Why can't I directly access (and lock) the implicit lock that Objects use for synchronized block 如何在不获取java.lang.IllegalMonitorStateException的情况下更改在同步块中获取的锁,对其进行更改以及notifyAll()? - how can I change the lock I have aquired in a synchronized block, change it, and notifyAll() without getting java.lang.IllegalMonitorStateException? 为什么Java锁实现中没有使用synchronized关键字? - Why is there no synchronized keyword used in Java lock implementations? 在同一函数的synchronized()块中初始化之后,是否可以在synchronized()之外安全地使用Java集合? - Can a Java collection be safely used outside of synchronized() after initializing in a synchronized() block in the same function? java:可以同步块交错吗? - java: can synchronized block interleave? Java 同步块:锁定块直到 object 实例化 - Java synchronized block: Lock block until object instantiated 当Integer对象用作同步块中的锁时,可能出现并发问题 - Potential concurrency issue when Integer object is used as a lock in synchronized block 我可以在Java中的同步块之外的共享字段上检查null吗? - Can I check for null on a shared field outside of a synchronized block in java? 为什么这个简单的Java同步代码块示例根据锁定的对象为我提供不同的输出? - Why is this simple Java synchronized code block example giving me different output, depending on which object I lock on? 同步块/代码Java上的线程访问 - Threads access on Synchronized Block/Code Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM