// 尝试获取写锁 protected final boolean tryAcquire(int acquires) { Thread current = Thread.currentThread(); int c = getState(); // 全状态 int w = exclusiveCount(c); // 写锁状态 if (c != 0) { // 情况1:全状态!=0 且写锁状态==0, 说明当前有读锁,此时不能获取写锁 // 情况2:写锁状态!=0 但是当前线程不是写锁拥有者,不能获取写锁 if (w == 0 || current != getExclusiveOwnerThread()) return false; // 当前线程是写锁拥有者,检查重入后次数是否超标 if (w + exclusiveCount(acquires) > MAX_COUNT) throw new Error("Maximum lock count exceeded"); // 执行重入操作,返回true setState(c + acquires); return true; } // 情况1:当前写锁应该等待 // 情况2:cas失败 if (writerShouldBlock() || !compareAndSetState(c, c + acquires)) return false; // cas成功 setExclusiveOwnerThread(current); return true; }
ReentrantReadWriteLock.Sync::tryAcquire
原文:https://www.cnblogs.com/jxzz/p/14777689.html