ReentrantLock实现探究

来源:互联网 发布:php简单后台html5源码 编辑:程序博客网 时间:2024/05/29 05:01
默认使用非公平锁;可通过构造参数指定使用公平锁还是非公平锁;
公平锁:尝试获取锁时总是会先判断当前队列里是否还有其他线程再等待该锁,如果没有才会尝试获取锁;

非公平锁:会先尝试自己获取锁,不管队列里是否有其他线程在等待该锁,获取成功则返回,失败则加入等待队列末尾,此时会按照FIFO的方式获取锁;


线程等待队列:使用链表数据结构,添加新线程使用CAS算法,头尾成员使用volatile关键字;CAS和volatile内存模型来保证线程同步;

某线程获取到锁之后,从链表中删除时主要调用到下面代码:

/**     * Acquires in exclusive uninterruptible mode for thread already in     * queue. Used by condition wait methods as well as acquire.     *     * @param node the node     * @param arg the acquire argument     * @return {@code true} if interrupted while waiting     */    final boolean acquireQueued(final Node node, int arg) {        boolean failed = true;        try {            boolean interrupted = false;            for (;;) {                final Node p = node.predecessor();                if (p == head && tryAcquire(arg)) {                    setHead(node);                    p.next = null; // help GC                    failed = false;                    return interrupted;                }                if (shouldParkAfterFailedAcquire(p, node) &&                    parkAndCheckInterrupt())                    interrupted = true;            }        } finally {            if (failed)                cancelAcquire(node);        }    }

删除时主要修改头结点即可,源码里是调用
setHead(node);
直接设置head=node,这部分代码其实不用同步,因为只有修改了头结点之后,其他线程才能尝试获取锁,不然仍是在等待;


0 0