公平模式ReentrantLock實(shí)現(xiàn)原理
前面的文章研究了AbstractQueuedSynchronizer的獨(dú)占鎖和共享鎖,有了前兩篇文章的基礎(chǔ),就可以乘勝追擊,看一下基于AbstractQueuedSynchronizer的并發(fā)類是如何實(shí)現(xiàn)的。
ReentrantLock顯然是一種獨(dú)占鎖,首先是公平模式的ReentrantLock,Sync是ReentractLock中的基礎(chǔ)類,繼承自AbstractQueuedSynchronizer,看一下代碼實(shí)現(xiàn):
1 abstract static class Sync extends AbstractQueuedSynchronizer { 2 private static final long serialVersionUID = -5179523762034025860L; 3 4 /** 5 * Performs {@link Lock#lock}. The main reason for subclassing 6 * is to allow fast path for nonfair version. 7 */ 8 abstract void lock(); 9 10 /**11 * Performs non-fair tryLock. tryAcquire is12 * implemented in subclasses, but both need nonfair13 * try for trylock method.14 */15 final boolean nonfairTryAcquire(int acquires) {16 &