第3天 ReentrantLock

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。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 摘要: 我们已经知道,synchronized 是Java的关键字,是Java的内置特性,在JVM层面实现了对临界...
    kingZXY2009阅读 1,845评论 0 20
  • Java并发总结 1.多线程的优点 资源利用率更好 程序在某些情况下更简单 程序响应更快 2.创建线程 1.实现R...
    不会上树的猴子阅读 1,041评论 0 5
  • Java-Review-Note——4.多线程 标签: JavaStudy PS:本来是分开三篇的,后来想想还是整...
    coder_pig阅读 1,682评论 2 17
  • 作者: 一字马胡 转载标志 【2017-11-03】 更新日志 前言 在java中,锁是实现并发的关键组件,多个...
    一字马胡阅读 44,196评论 1 32
  • 白灼的日光下就算孤独也不会害怕,哑光色薄薄地铺满整个画面,黏稠而富有弹性,轻轻地伸伸胳膊儿动动腿是扯不破的。当然,...
    我不会在这里发东西了阅读 565评论 3 2