java.concurrent.ReentrantLock-为什么我们要多次获取相同的锁 [英] java.concurrent.ReentrantLock - why we want to acquire the same lock multiple times

查看:529
本文介绍了java.concurrent.ReentrantLock-为什么我们要多次获取相同的锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道是否使用ReentrantLock,它允许同一线程多次获取同一锁.在内部,它有一个计数器来计算锁获取的次数.如果两次获取相同的锁,则需要释放两次.但是我的问题是,为什么有人要多次获取锁,一次获取就足够了吗?有人可以给我一个常见的用例吗?

I know if using ReentrantLock, it allows the same thread to acquire the same lock more than once. Internally, it has a counter to count the number of the lock acquisition. If you acquired the same lock twice, you would need to release it twice. But my question is that why would someone want to acquire the lock multiple times, should one time acquisition be enough? Can someone give me a common use case?

推荐答案

请考虑以下情况,在这种情况下,您需要一组不是原子的操作,而是原子的.例如,您可能想要设置一个数组的值,但是在设置时返回其当前值. (为简洁起见,请最终尝试删除.)

Consider the following case in which you need a set of operations which isn't atomic, be atomic. For example you may want to set a value of an array but return its current value upon setting. (try-finally removed for brevity).

final ReentrantLock lock = new ReentrantLock();

final Object[] objects = new Object[10]
public Object setAndReturnPrevious(int index, Object val){
   lock.lock();
      Object prev = get(index);
      set(index,val);
      return prev;
   lock.unlock();
}
public void set(int index, Object val){
    lock.lock();
         objects[index] = val;
    lock.unlock();
}
public Object get(index index){...}

如果没有重新进入ReentrantLock,您将在get(index)

If ReentrantLock wasn't reentrant you would deadlock at get(index)

这篇关于java.concurrent.ReentrantLock-为什么我们要多次获取相同的锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆