ReentrantLock 基於原始碼了解工作流程

2021-10-06 15:27:44 字數 2285 閱讀 4532

reentrantlock和synchronized在jdk1.8版本後效能相差無幾,甚至synchronized小優,但是synchronized不支援中斷和超時,也就是說通過synchronized一旦被阻塞住,如果一直無法獲取到所資源就會一直被阻塞,即使中斷也沒用,這對併發系統的效能影響太大了;lock支援中斷和超時、還支援嘗試機制獲取鎖,對synchronized進行了很好的擴充套件,所以從靈活性上lock是明顯優於synchronized的

基本方法

// 構造方法

// boolean fair 是否為公平鎖

reentrantlock

(boolean fair)

// 嘗試拿鎖,拿不到阻塞等待

void

lock()

;// 釋放鎖

void

unlock()

;// 等待拿鎖的時間可被中斷

void

lockinterruptibly()

throws interruptedexception;

// 嘗試拿鎖,不等待

boolean

trylock()

;// 嘗試拿鎖,等待timeout時間

boolean

trylock

(long timeout, timeunit unit)

throws interruptedexception;

公平鎖

拿鎖

final

void

lock()

public

final

void

acquire

(int arg)

//嘗試拿鎖

protected

final

boolean

tryacquire

(int acquires)

}// 當前有執行緒持有鎖

// 判斷當前持有鎖的執行緒是否是當前執行緒

else

if(current ==

getexclusiveownerthread()

)return

false

;}

// 將當前執行緒加入請求佇列

private node addwaiter

(node mode)

}// 佇列不存在 建立佇列 並 將當前請求放入佇列

enq(node)

;return node;

}

final

boolean

acquirequeued

(final node node,

int arg)

// 判斷當前執行緒請求狀態是否應該 parkif(

shouldparkafte***iledacquire

(p, node)

&&parkandcheckinterrupt()

)// 阻塞 locksupport.park(this);

interrupted =

true;}

}finally

}

釋放鎖
public

final

boolean

release

(int arg)

return

false

;}

protected

final

boolean

tryrelease

(int releases)

setstate

(c);

return free;

}

非公平鎖
final

void

lock()

protected

final

boolean

tryacquire

(int acquires)

final

boolean

nonfairtryacquire

(int acquires)

}else

if(current ==

getexclusiveownerthread()

)return

false

;}

基於ReentrantLock鎖解決超賣問題

service slf4j public class orderservice 商品當前庫存 integer currentcount product.getcount system.out.println thread.currentthread getname 庫存數 currentcount ...

ReentrantLock實現同步

reentrantlock 也可以實現synchronized方法 塊的同步效果。reentrantlock 實現同步 如下 1 新建乙個service類 public class myservice public static void methodb 2 新建乙個測試類 public class...

ReentrantLock之unlock方法分析

public void unlock public final boolean release int arg return false release 1 嘗試在當前鎖的鎖定計數 state 值上減1。成功返回true,否則返回false。當然在release 方法中不僅僅只是將state 1這麼...