ReentrantLock源码之公平锁的实现
作者:互联网
- 代码案例
public class ReentrantLockDemo {
public static void main(String[] args) {
ReentrantLock reentrantLock = new ReentrantLock(true);
reentrantLock.lock();
reentrantLock.unlock();
}
}
- 查看无参构造方法
public ReentrantLock() {
sync = new NonfairSync(); // new了1个非公平实现
}
-
查看sync
-
查看有参构造
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync(); // 为true时返回公平实现,否则返回非公平实现
}
-
ReentrantLock实现了Lock接口
-
查看方法
-
查看内部类
-
查看lock方法
public class ReentrantLockDemo {
public static void main(String[] args) {
ReentrantLock reentrantLock = new ReentrantLock(true);
reentrantLock.lock();
reentrantLock.unlock();
}
}
public void lock() {
sync.acquire(1);
}
public final void acquire(int arg) {
// 尝试获取锁
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) // 同时获取队列失败
selfInterrupt(); // 则线程终止
}
- 查看尝试获取锁的方法
protected boolean tryAcquire(int arg) {
throw new UnsupportedOperationException();
}
- 查看非公平实现
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
@ReservedStackAccess
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread(); // 获取当前线程
int c = getState(); // 获取状态
if (c == 0) { // 当前没有线程获取到这个锁
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true; // 获得锁
}
}
else if (current == getExclusiveOwnerThread()) { // 是否是持有锁的线程,即重入状态
int nextc = c + acquires; // 重入状态加1
if (nextc < 0) // overflow // 超过最大重入状态,抛出异常
throw new Error("Maximum lock count exceeded");
setState(nextc); // 更新
return true; // 获得锁
}
return false;
}
- 查看addWaiter方法
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
-
查看EXCLUSIVE
-
查看addWaiter方法
private Node addWaiter(Node mode) {
Node node = new Node(mode); // 传入参数,当前线程,new1个Node
for (;;) {
Node oldTail = tail; // 前置节点指向尾节点
if (oldTail != null) {
node.setPrevRelaxed(oldTail);
if (compareAndSetTail(oldTail, node)) { // node设置为尾节点
oldTail.next = node;
return node;
}
} else {
initializeSyncQueue(); // 若整条队列为null,执行入队
}
}
}
- 查看Node
Node(Node nextWaiter) {
this.nextWaiter = nextWaiter;
THREAD.set(this, Thread.currentThread());
}
标签:Node,查看,ReentrantLock,源码,公平,arg,new,public 来源: https://www.cnblogs.com/chniny/p/16269335.html