Skip to content

Commit 510273a

Browse files
committed
Update reentrantlock.md
1 parent a90e078 commit 510273a

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

docs/java/concurrent/reentrantlock.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,33 @@ private volatile int state;
218218

219219
![](https://p1.meituan.net/travelcube/b8b53a70984668bc68653efe9531573e78636.png)
220220

221+
> 🐛 修正: 图中的一处小错误,(AQS)CAS修改共享资源 State 成功之后应该是获取锁成功(非公平锁)。
222+
>
223+
> 对应的源码如下:
224+
>
225+
> ```java
226+
> final boolean nonfairTryAcquire(int acquires) {
227+
> final Thread current = Thread.currentThread();//获取当前线程
228+
> int c = getState();
229+
> if (c == 0) {
230+
> if (compareAndSetState(0, acquires)) {//CAS抢锁
231+
> setExclusiveOwnerThread(current);//设置当前线程为独占线程
232+
> return true;//抢锁成功
233+
> }
234+
> }
235+
> else if (current == getExclusiveOwnerThread()) {
236+
> int nextc = c + acquires;
237+
> if (nextc < 0) // overflow
238+
> throw new Error("Maximum lock count exceeded");
239+
> setState(nextc);
240+
> return true;
241+
> }
242+
> return false;
243+
> }
244+
> ```
245+
>
246+
>
247+
221248
为了帮助大家理解 ReentrantLockAQS 之间方法的交互过程,以非公平锁为例,我们将加锁和解锁的交互流程单独拎出来强调一下,以便于对后续内容的理解。
222249
223250
![](https://p1.meituan.net/travelcube/7aadb272069d871bdee8bf3a218eed8136919.png)

0 commit comments

Comments
 (0)