lock锁—unlock源码解析(锁释放)

本文详细解读了ReentrantLock的unlock方法,包括如何通过release方法释放锁资源,tryRelease如何减小锁状态并检查线程所有权,以及unparkSuccessor如何唤醒等待线程。通过对源码的分析,理解了锁释放的整个过程。
摘要由CSDN通过智能技术生成

之前已经搬运过lock锁的获取,现在看一下lock锁的锁释放方法(unlock)的源码,正如unlock的语义一样,unlock方法是Lock接口中定义的解锁方法,释放线程获取的资源,并通知等待线程获取资源。

/**
 * Attempts to release this lock.
 *
 * <p>If the current thread is the holder of this lock then the hold
 * count is decremented.  If the hold count is now zero then the lock
 * is released.  If the current thread is not the holder of this
 * lock then {@link IllegalMonitorStateException} is thrown.
 *
 * @throws IllegalMonitorStateException if the current thread does not
 *         hold this lock
 */
public void unlock() {
    sync.release(1);
}

在实现类ReentrantLock中,unlock方法很简单,就是调用了一下抽象内部类Sync中的release,可以说真正处理释放功能的正是release方法。

/**
 * Releases in exclusive mode.  Implemented by unblocking one or
 * more threads if {@link #tryRelease} returns true.
 * This method can be used to implement method {@link Lock#un
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值