File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff 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为了帮助大家理解 ReentrantLock 和 AQS 之间方法的交互过程,以非公平锁为例,我们将加锁和解锁的交互流程单独拎出来强调一下,以便于对后续内容的理解。
222249
223250! [](https: // p1.meituan.net/travelcube/7aadb272069d871bdee8bf3a218eed8136919.png)
You can’t perform that action at this time.
0 commit comments