ReentrantLock重入鎖肤寝,Lock的具體實(shí)現(xiàn)
public class ReentrantLock implements Lock, java.io.Serializable
Lock為顯示鎖,synchronized為內(nèi)部鎖。
- Lock支持更細(xì)粒度的鎖控制
- Lock是無(wú)阻塞鎖菇篡, synchronized是阻塞鎖
- Lock可實(shí)現(xiàn)公平鎖, synchronized只能是非公平鎖
- Lock是代碼級(jí)的赶诊, synchronized是JVM級(jí)的
/**
* Linked list node class
* 節(jié)點(diǎn)數(shù)據(jù)結(jié)構(gòu)笼平,可以發(fā)現(xiàn)為單向鏈表
*/
static class Node<E> {
E item;
/**
* One of:
* - the real successor Node
* - this Node, meaning the successor is head.next
* - null, meaning there is no successor (this is the last node)
*/
Node<E> next;
Node(E x) { item = x; }
}
/** Current number of elements
* 當(dāng)前數(shù)量,使用原子計(jì)數(shù), 保證多線程安全
* */
private final AtomicInteger count = new AtomicInteger();
/** Lock held by take, poll, etc */
private final ReentrantLock takeLock = new ReentrantLock();
/** Wait queue for waiting takes */
private final Condition notEmpty = takeLock.newCondition();
/** Lock held by put, offer, etc */
private final ReentrantLock putLock = new ReentrantLock();
/** Wait queue for waiting puts */
private final Condition notFull = putLock.newCondition();
通過(guò)重入鎖的方式舔痪,實(shí)現(xiàn)讀寫(xiě)分離鎖寓调。并使用condition保證在滿足特定條件時(shí),線程block锄码。