# 一张图读懂非公平锁与公平锁

``````  //非公平锁
final boolean nonfairTryAcquire(int acquires) {
int c = getState();
if (c == 0) {
//区别重点看这里
if (compareAndSetState(0, acquires)) {
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}

//公平锁
protected final boolean tryAcquire(int acquires) {
int c = getState();
if (c == 0) {
//hasQueuedPredecessors这个方法就是最大区别所在
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
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;
}
``````

1、若在释放锁的时候总是没有新的兔子来打扰，则非公平锁等于公平锁；
2、若释放锁的时候，正好一个兔子来喝水，而此时位于队列头的兔子还没有被唤醒（因为线程上下文切换是需要不少开销的），此时后来的兔子则优先获得锁，成功打破公平，成为非公平锁；

``````private void unparkSuccessor(Node node) {
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);

Node s = node.next;
if (s == null || s.waitStatus > 0) {
s = null;
for (Node t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;
}
if (s != null)
//唤醒队列头的线程