> 文章列表 > ReetrantLock源码剖析_02内部类NoFairSync、构造器

ReetrantLock源码剖析_02内部类NoFairSync、构造器

ReetrantLock源码剖析_02内部类NoFairSync、构造器

ReetrantLock内部类NoFairSync代码解析

NoFairSyncReetrantLock公平锁的主要实现类,NoFairSync继承了Sync

/* 继承自Sync,实现非公平锁*/static final class NonfairSync extends Sync {private static final long serialVersionUID = 7316153563782823691L;/* 加锁*/final void lock() {//如果CAS成功,就将state从0设置为1//并且将当前线程设置为锁的持有者if (compareAndSetState(0, 1))setExclusiveOwnerThread(Thread.currentThread());else//如果CAS失败,否则就调用父类AQS的acquire方法进行加锁acquire(1);}//尝试获取锁protected final boolean tryAcquire(int acquires) {//调用父类Sync的nonfairTryAcquire方法return nonfairTryAcquire(acquires);}}

ReetrantLock构造器代码解析

无参构造器:

/* 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();}

英语口语