原理与概念

       1.ReentrantLock原理:多个线程获取锁,一个线程获取到锁,其他线程排队等待锁,并挂起;当获取到锁这个节点释放锁,就会唤醒队伍的头结点。

   2.ReentrantLock是个可重入锁,支持公平锁和非公平锁。ReentrantLock默认使用非公平锁,看源码可知。

       

    /**
     * Creates an instance of {@code ReentrantLock}.
     * This is equivalent to using {@code ReentrantLock(false)}.
     */
    public ReentrantLock() {
        sync = new NonfairSync();
    }

 

      3.可重入锁就是一个线程获得了一个锁,再重复的获取这个锁不会死锁。注意是重复获取相同的锁。

      4.非公平锁就是当前线程每次获取锁,获取不到在排队。

      5.公平锁就是都是获取锁的顺序按队伍的顺序来,当前线程不会去获取锁,直接取排队。

      6.ReentrantLock是利用AQS实现,AQS就是定义了一个依赖于先进先出队列来实现阻塞锁和同步器的框架。

    7.首先先了解下ReentrantLock的锁的几个重要的变量,锁实现全靠它们

    

    //锁的状态,0无锁,1有线程获取到锁,>1记录重复获取锁的次数
    /**
     * The synchronization state.
     */
    private volatile int state;
    //等待队列是个循环链表
    //头结点
    /**
     * Head of the wait queue, lazily initialized.  Except for
     * initialization, it is modified only via method setHead.  Note:
     * If head exists, its waitStatus is guaranteed not to be
     * CANCELLED.
     */
    private transient volatile Node head;
    //尾节点
    /**
     * Tail of the wait queue, lazily initialized.  Modified only via
     * method enq to add new wait node.
     */
    private transient volatile Node tail;
    //当前获取锁的线程
   /**
     * The current owner of exclusive mode synchronization.
     */
    private transient Thread exclusiveOwnerThread;

 

   

posted on 2020-03-26 21:20  柳无情  阅读(2276)  评论(0编辑  收藏  举报