juc包中,aqs實現的公平鎖和非公平鎖的最主要的區別是:非公平鎖中,那些嘗試擷取鎖且尚未進入等待隊列的線程會和等待隊列head結點的線程發生競爭。公平鎖中,在擷取鎖時,增加了isFirst(current)判斷,若且唯若,等待隊列為空白或當前線程是等待隊列的頭結點時,才可嘗試擷取鎖。
1.1 NonfairSync.lock() Java代碼 final void lock() { if (compareAndSetState(0, 1))//沒有進入等待隊列,也可以擷取鎖 setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); }
2.1 FairSync.lock() Java代碼 final void lock() { acquire(1); }
2.2 FairSync.tryAcquire() Java代碼 /** * Fair version of tryAcquire. Don't grant access unless * recursive call or no waiters or is first. */ protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { if (isFirst(current) &&//只有等待隊列為空白或當前線程是隊列頭結點才可以擷取鎖 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; }
關於當前線程是否是隊列頭結點的判斷,詳見下面兩個函數:
2.3 AbstractQueuedSynchronizer.isFirst() Java代碼 /** * Return {@code true} if the queue is empty or if the given thread * is at the head of the queue. This is reliable only if * <tt>current</tt> is actually Thread.currentThread() of caller. */ final boolean isFirst(Thread current) { Node h, s; return ((h = head) == null || ((s = h.next) != null && s.thread == current) || fullIsFirst(current)); }
2.4 AbstractQueuedSynchronizer.fullIsFirst() Java代碼 final boolean fullIsFirst(Thread current) { // same idea as fullGetFirstQueuedThread Node h, s; Thread firstThread = null; if (((h = head) != null && (s = h.next) != null && s.prev == head && (firstThread = s.thread) != null)) return firstThread == current; Node t = tail; while (t != null && t != head) { Thread tt = t.thread; if (tt != null) firstThread = tt; &nbs