/** Returns the number of shared holds represented in count */ // 读锁是共享锁 staticintsharedCount(int c){ return c >>> SHARED_SHIFT; } /** Returns the number of exclusive holds represented in count */ // 写锁是独占锁 staticintexclusiveCount(int c){ return c & EXCLUSIVE_MASK; }
protectedfinalbooleantryReleaseShared(int unused){ Thread current = Thread.currentThread(); // 前面还是为了实现getReadHoldCount等新功能 if (firstReader == current) { // assert firstReaderHoldCount > 0; if (firstReaderHoldCount == 1) firstReader = null; else firstReaderHoldCount--; } else { HoldCounter rh = cachedHoldCounter; if (rh == null || rh.tid != getThreadId(current)) rh = readHolds.get(); int count = rh.count; if (count <= 1) { readHolds.remove(); if (count <= 0) throw unmatchedUnlockException(); } --rh.count; } for (;;) { int c = getState(); // 读锁释放 将同步状态减去读状态即可 int nextc = c - SHARED_UNIT; if (compareAndSetState(c, nextc)) // Releasing the read lock has no effect on readers, // but it may allow waiting writers to proceed if // both read and write locks are now free. return nextc == 0; } }