ReentrantLock重入锁,Lock的具体实现
public class ReentrantLock implements Lock, java.io.Serializable
Lock为显示锁,synchronized为内部锁。
- Lock支持更细粒度的锁控制
- Lock是无阻塞锁, synchronized是阻塞锁
- Lock可实现公平锁, synchronized只能是非公平锁
- Lock是代码级的, synchronized是JVM级的
/**
* Linked list node class
* 节点数据结构,可以发现为单向链表
*/
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
* 当前数量,使用原子计数, 保证多线程安全
* */
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();
通过重入锁的方式,实现读写分离锁。并使用condition保证在满足特定条件时,线程block。