可重入锁 ReentrantLock 源码解读 (2)锁框架 AbstractQueuedSynchronizer

Provides a framework for implementing blocking locks and related  synchronizers (semaphores, events, etc) that rely on  first-in-first-out (FIFO) wait queues. 

如java API AbstractQueuedSynchronizer文档所言--其是为方便实现依赖于先进先出等待队列的阻塞锁和相关的同步器(semaphores -信号量,events )提供的一种框架。


FIFO队列:每个节点代表一个线程

 static final class Node {
        static final Node SHARED = new Node(); //说明节点的类型--共享的还是独占的
        static final Node EXCLUSIVE = null;

        static final int CANCELLED =  1; //等待状态--表示需要把这个线程从阻塞队列中移除
        static final int SIGNAL    = -1; //表示这个线程可以获得锁
        static final int CONDITION = -2; //表示这个线程在执行条件等待--condition.await()
        static final int PROPAGATE = -3; //共享锁的等待状态

        volatile int waitStatus; //volatile 线程的状态更行对其它线程可见

        volatile Node prev; //前节点

        volatile Node next; //后节点

        /**
         * The thread that enqueued this node.  Initialized on
         * construction and nulled out after use.
         */
        volatile Thread thread;


        Node nextWaiter;

        /**
         * Returns true if node is waiting in shared mode
         */
        final boolean isShared() {
            return nextWaiter == SHARED;
        }

        final Node predecessor() throws NullPointerException {
            Node p = prev;
            if (p == null)
                throw new NullPointerException();
            else
                return p;
        }

        Node() {    // Used to establish initial head or SHARED marker
        }

        Node(Thread thread, Node mode) {     // Used by addWaiter
            this.nextWaiter = mode;
            this.thread = thread;
        }

        Node(Thread thread, int waitStatus) { // Used by Condition
            this.waitStatus = waitStatus;
            this.thread = thread;
        }
    }


让我们从ReentrantLock调用序列开始了解:

 ReentrantLock 

         |------lock()

                     |----------acquire()

                                          |-------------tryAcquire()                             //尝试申请锁 若失败则加入等待队列

                                          |-------------acquireQueued()           

                                                                             |-------------------addWaiter() //将申请锁失败而阻塞的线程加入到队列末尾



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值