公平锁、非公平锁的区别 发表于 2022-02-11 | 分类于 ---Java-并发 | 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 static final class FairSync extends Sync { private static final long serialVersionUID = -3000897897090466540L; final void lock() { acquire(1); } // tryAcquire 的公平版本。除非递归调用或没有等待者或者是第一个等待者,否则不要授予访问权限。 protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } } public final boolean hasQueuedPredecessors() { Node t = tail; Node h = head; Node s; return h != t && ((s = h.next) == null || s.thread != Thread.currentThread()); }// 只有 hasQueuedPredecessors 返回 false 才能获取到锁//// hasQueuedPredecessors 的意思是:没有排队的前辈//// 只有两种情况会获取到锁:// [获取锁的情况1] 队列中没有节点// h==t 获取锁//// [获取锁的情况2] 队列中有节点,并且队头的下一个 h.next 是当前线程// h!=t// h.next != null && h.next.thread == 当前