1.类定义
/*** 基于AQS的可重入锁 可定义公平与非公平*/
public class ReentrantLock implements Lock, java.io.Serializable {
}
1.1 Lock接口
/*** 定义锁接口* 接口支持那些语义不同(重入、公平等)的锁规则,可以在非阻塞式结构的上下文(包括 hand-over-hand 和锁重排算法)中使用这些规则。* 主要的实现是 ReentrantLock。*/
public interface Lock {/*在Lock中声明了四个方法来获取锁,那么这四个方法有何区别呢?* 首先,lock()方法是平常使用得最多的一个方法,就是用来获取锁。* 如果锁已被其他线程获取,则进行等待。* 在前面已经讲到,如果采用Lock,必须主动去释放锁,并且在发生异常时,不会自动释放锁。* 因此,一般来说,使用Lock必须在try…catch…块中进行,并且将释放锁的操作放在finally块中进行,以保证锁一定被被释放,防止死锁的发生。*//** 获取锁 */void lock();/*lockInterruptibly()方法比较特殊,当通过这个方法去获取锁时,* 如果线程 正在等待获取锁,则这个线程能够 响应中断,即中断线程的等待状态。* 例如,当两个线程同时通过lock.lockInterruptibly()想获取某个锁时,假若此时线程A获取到了锁,而线程B只有在等待,* 那么对线程B调用threadB.interrupt()方法能够中断线程B的等待过程。*//** 如果当前线程未被中断,则获取锁,可以响应中断 */void lockInterruptibly() throws InterruptedException;/*tryLock()方法是有返回值的,它表示用来尝试获取锁,如果获取成功,则返回true;* 如果获取失败(即锁已被其他线程获取),则返回false,* 也就是说,这个方法无论如何都会立即返回(在拿不到锁时不会一直在那等待)*//** 仅在调用时锁为空闲状态才获取该锁,可以响应中断 */boolean tryLock();/*tryLock(long time, TimeUnit unit)方法和tryLock()方法是类似的,* 只不过区别在于这个方法在拿不到锁时会等待一定的时间,在时间期限之内如果还拿不到锁,就返回false,* 同时可以响应中断。如果一开始拿到锁或者在等待期间内拿到了锁,则返回true。*//** 如果锁在给定的等待时间内空闲,并且当前线程未被中断,则获取锁 */boolean tryLock(long time, TimeUnit unit) throws InterruptedException;/** 释放锁 */void unlock();/** 返回绑定到此 Lock 实例的新 Condition 实例 */Condition newCondition();
}
2.ReentrantLock中的同步器
public class ReentrantLock implements Lock, java.io.Serializable {private static final long serialVersionUID = 7373984872572414699L;private final Sync sync;/** 定义抽象静态内部类Sync继承抽象类AbstractQueuedSynchronizer */abstract static class Sync extends AbstractQueuedSynchronizer {private static final long serialVersionUID = -5179523762034025860L;abstract void lock();/** 非公平的尝试获取锁 */final boolean nonfairTryAcquire(int acquires) {final Thread current = Thread.currentThread(); //当前线程int c = getState(); //当前状态if (c == 0) { //锁还未同步if (compareAndSetState(0, acquires)) { //将State修改为acquiressetExclusiveOwnerThread(current); //设置当前线程 return true; //操作成功 }}else if (current == getExclusiveOwnerThread()) { //锁以同步,判断是否为当前线程同步int nextc = c + acquires;if (nextc < 0) // overflowthrow new Error("Maximum lock count exceeded");setState(nextc); //设置State值return true; //获取锁成功}return false; //获取锁失败}/*** 尝试释放*/protected final boolean tryRelease(int releases) {int c = getState() - releases;if (Thread.currentThread() != getExclusiveOwnerThread()) //若加锁线程不是当前线程,直接抛出异常throw new IllegalMonitorStateException();boolean free = false; //是否完全释放if (c == 0) {free = true; //完全释放 设置值为truesetExclusiveOwnerThread(null); //设置加锁线程为null}setState(c); //设置状态return free; //返回是否完全释放}/** 判断是否为当前线程持有锁 */protected final boolean isHeldExclusively() {return getExclusiveOwnerThread() == Thread.currentThread();}/** 创建一个ConditionObject对象 */final ConditionObject newCondition() {return new ConditionObject();}/** 获取锁的当前持有线程 */final Thread getOwner() {return getState() == 0 ? null : getExclusiveOwnerThread();}/** 获取锁的重入次数 */final int getHoldCount() {return isHeldExclusively() ? getState() : 0;}/** 当前锁是否被使用 */final boolean isLocked() {return getState() != 0;}private void readObject(java.io.ObjectInputStream s)throws java.io.IOException, ClassNotFoundException {s.defaultReadObject();setState(0);}}/*** 定义静态内部类NonfairSync(非公平)继承Sync*/static final class NonfairSync extends Sync {private static final long serialVersionUID = 7316153563782823691L;final void lock() {if (compareAndSetState(0, 1)) //修改status为1setExclusiveOwnerThread(Thread.currentThread()); //记录当前线程elseacquire(1); //获取独占锁,对中断不敏感}protected final boolean tryAcquire(int acquires) {return nonfairTryAcquire(acquires);}}/*** 定义静态内部类FairSync(公平)继承Sync*/static final class FairSync extends Sync {private static final long serialVersionUID = -3000897897090466540L;final void lock() {acquire(1);}protected final boolean tryAcquire(int acquires) {final Thread current = Thread.currentThread();int c = getState();if (c == 0) {if (!hasQueuedPredecessors() &&compareAndSetState(0, acquires)) {setExclusiveOwnerThread(current);return true;}}else if (current == getExclusiveOwnerThread()) {int nextc = c + acquires;if (nextc < 0)throw new Error("Maximum lock count exceeded");setState(nextc);return true;}return false;}}
}
3.构造方法-指定同步器类型并初始化同步器
/*** 构造方法 默认sync赋值非公平的NonfairSync实现*/public ReentrantLock() {sync = new NonfairSync();}/*** 构造方法 根据入参初始化sync赋值*/public ReentrantLock(boolean fair) {sync = fair ? new FairSync() : new NonfairSync();}
4.方法实现-调用同步器方法进行操作处理
/*** 加锁*/public void lock() {sync.lock();}public void lockInterruptibly() throws InterruptedException {sync.acquireInterruptibly(1);}/*** 尝试获取锁 获取失败返回false*/public boolean tryLock() {return sync.nonfairTryAcquire(1);}/*** 尝试获取锁*/public boolean tryLock(long timeout, TimeUnit unit)throws InterruptedException {return sync.tryAcquireNanos(1, unit.toNanos(timeout));}/*** 释放锁*/public void unlock() {sync.release(1);}/** 创建一个ConditionObject对象 */public Condition newCondition() {return sync.newCondition();}/** 获取锁的重入次数 */public int getHoldCount() {return sync.getHoldCount();}/** 判断是否为当前线程持有锁 */public boolean isHeldByCurrentThread() {return sync.isHeldExclusively();}/** 判断当前锁是否被占用 */public boolean isLocked() {return sync.isLocked();}/** 判断当前锁是否公平锁 */public final boolean isFair() {return sync instanceof FairSync;}/** 获取占有当前锁的线程 */protected Thread getOwner() {return sync.getOwner();}/** 等待队列中是否还有线程 */public final boolean hasQueuedThreads() {return sync.hasQueuedThreads();}/** 线程是否在等待队列中 */public final boolean hasQueuedThread(Thread thread) {return sync.isQueued(thread);}/** 获取等待队列长度 */public final int getQueueLength() {return sync.getQueueLength();}/** 获取等待队列中的所有线程 */protected Collection<Thread> getQueuedThreads() {return sync.getQueuedThreads();}/** 获取condition.await中是否有数据 */public boolean hasWaiters(Condition condition) {if (condition == null)throw new NullPointerException();if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))throw new IllegalArgumentException("not owner");return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);}/** 获取condition.await中的线程数量 */public int getWaitQueueLength(Condition condition) {if (condition == null)throw new NullPointerException();if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))throw new IllegalArgumentException("not owner");return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);}/** 获取condition.await中的线程 */protected Collection<Thread> getWaitingThreads(Condition condition) {if (condition == null)throw new NullPointerException();if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))throw new IllegalArgumentException("not owner");return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);}