面试向:什么是Reentrant Lock?

本文介绍了可重入锁的基本概念及其在Java中的实现方式。它允许持有锁的线程多次进入同一资源,并提供了公平锁机制确保等待最久的线程有机会获取锁。文章还详细解释了如何使用ReentrantLock类来实现这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于可重入锁,我们目前都知道些什么?
我知道这个class implement Lock interface. 是一种比较高级的锁。

还是三个核心问题:
what is reentrant lock? why would we use it? how to use it?

reentrant lock is a class implement the Lock interface, and provides synchroniation to to methods while accessing resources.
it’s like the keyword synchronized.

it has two features:

  1. allows threads to enter into the lock on a resource more than one. it has a counter in it. each time we reenter, count plus 1.and for each unlock request, it minues one. so when the hold count is 0, the resource is unlocked.
  2. it also offers a fairness mechanism. just set true in it’s constructor. which means, the lock will go to the threads which wait for the longest time.

How to use it?
methods in ReentrantLock() class:
lock()
unlock()
tryLock()
getHoldCount()
可以看出大多数都是从lock()里面搞过来的。
使用步骤:
3. Create an object of ReentrantLock
4. Create a worker(Runnable Object) to execute and pass the lock to the object
5. Use the lock() method to acquire the lock on shared resource
6. After completing work, call unlock() method to release the lock

Reentrant Lock in Java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值