Lock鎖分為公平鎖和非公平鎖兩種
公平鎖:線程獲取鎖的順序是按照線程加鎖的順序來分配的,即先來先得的FIFO先進先出順序
非公平鎖:一種獲取鎖的搶占機制,是隨機獲取鎖的,和公平鎖的區別就是先來的不一定先得到鎖,導致某些線程可能一直拿不到鎖,所以是不公平的
公平鎖,就是很公平,在並發環境中,每個線程在獲取鎖時會先查看此鎖維護的等待隊列,如果為空,或者當前線程是等待隊列的第一個,就占有鎖,否則就會加入到等待隊列中,以后會按照FIFO的規則從隊列中取到自己;非公平鎖比較粗魯,上來就直接嘗試占有鎖,如果嘗試失敗,就再采用類似公平鎖那種方式
--------------------------------------公平鎖--------------------------------------
protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) {//狀態是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() { // The correctness of this depends on head being initialized // before tail and on head.next being accurate if the current // thread is first in queue. Node t = tail; // Read fields in reverse initialization order Node h = head; Node s; return h != t && ((s = h.next) == null || s.thread != Thread.currentThread()); }
--------------------------------------非公平鎖--------------------------------------
final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); 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; }
