继承Lock接口
方法 | 说明 |
void lock() | 获取锁。如果锁被占用,那么当前线程阻塞,直到锁被获取。 |
void lockInterruptibly() | 获取锁,同lock方法,支持线程中断响应。 |
boolean tryLock() | 获取锁时,如果没有被其他线程占用立即返回true,否则返回false。 |
boolean tryLock(long time, TimeUnit unit) throws InterruptedException; | 在给定的时间内获取锁,支持线程中断响应。 |
void unlock() | 释放锁。 |
Condition newCondition() | 生成Condition实例,提供await、signal等方法,调用这些方法必须先获取锁操作。 |
公平锁和非公平锁
ReentrantLock默认构造函数为非公平锁。
ReentrantLock(boolean fair) fair参数true:公平锁,false:非公开锁
/**
* Creates an instance of {@code ReentrantLock}.
* This is equivalent to using {@code ReentrantLock(false)}.
*/
public ReentrantLock() {
sync = new NonfairSync();
}
/**
* Creates an instance of {@code ReentrantLock} with the
* given fairness policy.
*
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
公平性体现在获取锁方法上,公平锁实现的tryAcquire方法先查看队列中是否有等待的节点,完全按照FIFO原则。
tryLock()即使设置了公平策略,该方法也会通过非公平方法立即获取锁。