之前的acquire函數(shù)會先調用tryAcquire去嘗試獲得鎖,這個在每個具體類中實現(xiàn),這里看ReentrantLock中2個實現(xiàn)。
公平鎖FairSync中:
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {//狀態(tài)為0表示可以加鎖
if (!hasQueuedPredecessors() && //hasQueuedPredecessors表示之前的線程是否有在排隊的,這里加了!表示沒有排隊
compareAndSetState(0, acquires)) { //那么就去嘗試cas state
setExclusiveOwnerThread(current); //如果cas成功設置排他線程為當前線程截粗,表示成功得到鎖
return true;
}
}
else if (current == getExclusiveOwnerThread()) {//如果當前的排他線程是當前線程信姓,表示是重入
int nextc = c + acquires; //重入計數(shù)器增加
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);//因為已經(jīng)獲得鎖了,所以不用cas去設绸罗,直接設值就行
return true;
}
return false;
}
非公平鎖中:
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {//不同于公平鎖中意推,沒有hasQueuedPredecessors這個函數(shù),表示當非公平鎖去加鎖的時候从诲,不會去看有沒有線程在排隊左痢,直接去搶鎖,如果搶到了后續(xù)一樣系洛。否則會去排隊(后續(xù)代碼再看)
//之前課程上講過”一朝排隊永遠排隊“就是這個意思俊性,排隊中的非公平并不會去搶先
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;
}