开发乱炖

第3天 ReentrantLock

2017-07-17  本文已影响3人  TinyKing86

ReentrantLock重入锁,Lock的具体实现

public class ReentrantLock implements Lock, java.io.Serializable 

Lock为显示锁,synchronized为内部锁。

 /**
 * 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。

上一篇 下一篇

猜你喜欢

热点阅读