ReentrantLock源码解读及流程图
2022-04-17 21:27:37 0 举报
ReentrantLock源码解读及流程图
作者其他创作
大纲/内容
unlock()
compareAndSetWaitStatus(SIGNAL);
Yes
FairSync
tryRelease(int releases)
acquire(1)
公平锁是直接发起acquire
tryAcquire()
Sync
tryAcquire(arg)
pred.waitStatus > 0
do..while
tryAcquire(int acquires)
lock()
No
实现
发起请求
pred.waitStatus == Node.SIGNAL
cancelAcquire(Node node)
为什么可重入
setExclusiveOwnerThread(Thread.currentThread())
acquireQueued()
release()
继承
protected final void setExclusiveOwnerThread(Thread thread) { exclusiveOwnerThread = thread; } // private transient Thread exclusiveOwnerThread; 在AQS父类中有一个属性exclusiveOwnerThread; 用来标识当前持有锁的线程对象。
NonFairSync lock()源码解读
node.prev = pred = pred.prev;
parkAndCheckInterrupt()
hasQueuedPredecessors()
公平锁
addWaiter(Node mode)
Lock
addWaiter(Node.EXCULSIVE)
protected final boolean tryRelease(int releases) { //获取当前状态值减去参数值 int c = getState() - releases; if (Thread.currentThread() != getExclusiveOwnerThread()) throw new IllegalMonitorStateException(); boolean free = false; // c == 0 代表state 已经释放了所有的锁次数 if (c == 0) { free = true; //将当前代表独占锁属性置空 setExclusiveOwnerThread(null); } //初始化state值为0 setState(c); return free; }
锁流程图
什么是ReentrantLock
current == exclusiveOwnerThread
举例一个场景: 银行排队。只能有一个人进去办理业务,其他人排队。span style=\"font-size: inherit;\
enq(final Node node)
ReentrantLock
setExclusiveOwnerThread(Thread thread)
什么是中断操作?
非公平锁独有方法
null == tail
场景需求
NonFairSync
selfInterrupt()
final void lock() { acquire(1); }
enq(node)
shouldParkAfterFailedAcquire()
非公平锁
ReentrantLock结构组成
public void unlock() { sync.release(1); }
public final boolean release(int arg) { //尝试释放锁 if (tryRelease(arg)) { Node h = head; if (h != null && h.waitStatus != 0) //唤醒后继节点或从尾节点扫描状态值正常的且距离h节点最近的节点 unparkSuccessor(h); return true; } return false; }
NonFairSync unlock()源码分析
什么是中断操作
AbstractQueuedSynchronizer
unparkSuccessor(Node node)
enq()
提供了关于锁的操作规范
addWaiter()
acquire(int arg)
head ==node.predecessor()
setState(getState()+1)
compareAndSetHead(new Node())
0 条评论
下一页