并发编程原理与实战(十七)Lock接口API详解与优势举例

上一篇学习了为什么需要Lock接口,相比synchronized关键字Lock接口具有更灵活的锁控制能力‌,本文来进一步学习Lock接口的相关方法。

Lock核心API详解

Lock接口是JDK1.5之后引入的并发工具,声明的方法并不多,只有6个,是对锁的主要特性(上锁和解锁)的核心抽象。

1、lock()

在这里插入图片描述

/**
 * Acquires the lock.
 *
 * <p>If the lock is not available then the current thread becomes
 * disabled for thread scheduling purposes and lies dormant until the
 * lock has been acquired.
 *
 * <p><b>Implementation Considerations</b>
 *
 * <p>A {@code Lock} implementation may be able to detect erroneous use
 * of the lock, such as an invocation that would cause deadlock, and
 * may throw an (unchecked) exception in such circumstances.  The
 * circumstances and the exception type must be documented by that
 * {@code Lock} implementation.
 */
void lock();

线程调用该方法将获取锁,若锁不可用,则出于线程调度目的,当前线程将被禁止执行并进入休眠状态,直至成功获取锁。实现注意事项:Lock接口的具体实现类可检测锁的错误使用(如可能导致死锁的调用),并在该场景下抛出(非受检)异常。具体场景及异常类型必须由实现类说明。

2、lockInterruptibly()

/**
 * Acquires the lock unless the current thread is
 * {@linkplain Thread#interrupt interrupted}.
 ...
 * @throws InterruptedException if the current thread is
 *         interrupted while acquiring the lock (and interruption
 *         of lock acquisition is supported)
 */
void lockInterruptibly() throws InterruptedException;

调用该方法将获取锁,和lock()方法最大的区别是支持线程中断,在阻塞期间响应中断,避免死等

3、tryLock()

/**
 * Acquires the lock only if it is free at the time of invocation.
 *
 * <p>Acquires the lock if it is available and returns immediately
 * with the value {@code true}.
 * If the lock is not available then this method will return
 * immediately with the value {@code false}.
 *
 * <p>A typical usage idiom for this method would be:
 * <pre> {@code
 * Lock lock = ...;
 * if (lock.tryLock()) {
 *   try {
 *     // manipulate protected state
 *   } finally {
 *     lock.unlock();
 *   }
 * } else {
 *   // perform alternative actions
 * }}</pre>
 *
 * This usage ensures that the lock is unlocked if it was acquired, and
 * doesn't try to unlock if the lock was not acquired.
 *
 * @return {@code true} if the lock was acquired and
 *         {@code false} otherwise
 */
boolean tryLock();

仅当调用时锁处于空闲状态才获取锁。若锁可用则立即获取,返回true;若锁不可用则立即返回false。典型使用模式:

Lock lock = ...;
if (lock.tryLock()) {
   
   
    try {
   
   
      //操作受保护资源
    } finally 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

帧栈

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值