上一篇学习了为什么需要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

最低0.47元/天 解锁文章
170万+

被折叠的 条评论
为什么被折叠?



