参考kangjianwei大佬的LearningJDK
概述
类图
获得锁操作委托给继承了AQS的内部类Sync
FairSync和NonfairSync继承自Sync,分别实现公平和非公平的tryAcquire方法
调用解释
当调用reentrantLock().lock()
时,调用sync.aquire(1)
,即aqs.aquire(1)
,然后aqs.tryAquire()
,实际上是fairSync.tryAcquire()
或nonfairSync.tryAcquire()
,即sync.fairTryAquire()
和sync.nonfairTryAquire()
,尝试获取锁获取不到的话,则aqs.addWaiter()
,在同步队列中排队,之后aqs.acquireQueued()
从队列中申请,如果申请不到的话,则aqs.selfInterrupt()
,阻塞线程.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| @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()) { return false; } int nextc = c + acquires; if(nextc<0) { throw new Error("Maximum lock count exceeded"); } setState(nextc); return true; } return false; }
final boolean fairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if(c == 0) { if(!hasQueuedPredecessors()) { if(compareAndSetState(0, acquires)){ setExclusiveOwnerThread(current); return true; } } } else { if(current != getExclusiveOwnerThread()) { return false; } int nextc = c + acquires; if(nextc<0) { throw new Error("Maximum lock count exceeded"); } setState(nextc); return true; } return false; }
|
nonfairTryAcquire和fairTryAcquire区别在于fairTryAcquire判断了是否有正在排队的其他线程