ReentrantLock解析

ReentrantLock lock = new ReentrantLock();//默认非公平锁
lock.lock();//调用顺序 NonfairSync.lock(),成功则设置线程独占,失败则AbstractQueuedSynchronizer.acquire(1)[[[ 失败就                                  //acquireQueued(addWaiter()),acquire这里调用NonfairSync.tryAcquire(),tryAcquire中调用Syn.nonfairTryAcquire()]]]

lock.unlock();
            //AQS.release()然后调用Syn.tryRelease()
            //释放成功则唤醒下一个节点

ReentrantLock fairlock=new ReentrantLock(true);
fairlock.lock();//调用顺序 NonfairSync.lock(),直接调用AQS.acquire(1),acquire[[[中先调用FairSync.tryAcquire(1)  失败就AQS.acquireQueued(addWaiter())  ]]]
    //tryAcquire中hasQueuedPredecessors()通过判断"当前线程"是不是在CLH队列的队首,来返回AQS中是不是有比“当前线程”等待更久的线程,   有等待更久的就不获取锁

fairlock.unlock();

public class ReentrantLock implements Lock{
    private final Sync sync;//组合

    abstract static class Sync extends AbstractQueuedSynchronizer {
        abstract void lock();

        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

        protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }

    }    

    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        final void lock() {
            acquire(1);
        }

        /**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
    }

    

public abstract class AbstractOwnableSynchronizer {
   private transient Thread exclusiveOwnerThread;  
   protected final void setExclusiveOwnerThread(Thread thread) {
        exclusiveOwnerThread = thread;
    }
   protected final void getExclusiveOwnerThread {
        return exclusiveOwnerThread;
    }//标记是否独占线程
}

public abstract class AbstractQueuedSynchronizer extends AbstractOwnableSynchronizer{
    static final class Node {
         static final Node SHARED = new Node(); /** Marker to indicate a node is waiting in shared mode */

         static final Node EXCLUSIVE = null; /** Marker to indicate a node is waiting in exclusive mode */

         static final int CANCELLED =  1;   /**在同步队列中等待的线程等待超时或被中断,需要从同步队列中取消该Node的结点即结束状态,*进入该状态后的结点将不会再变化*/
       static final int SIGNAL    = -1;  /**处于唤醒状态,只要前继结点释放锁,就会通知标识为SIGNAL状态的后继结点的线程执行*/

  static final int CONDITION = -2; /** 该标识的结点处于等待队列中,结点的线程等待在Condition上,当其他线程调用了Condition
                                         的signal()方法后,CONDITION状态的结点将从等待队列转移到同步队列中,等待获取同步锁*/

         static final int PROPAGATE = -3;// 与共享模式相关,在共享模式中,该状态标识结点的线程处于可运行状态
                                         //使用在共享模式头结点有可能处于这种状态,表示锁的下一次获取可以无条件传播
         volatile int waitStatus;

         volatile Node prev;    volatile Node next;    volatile Thread thread;      Node nextWaiter;

         final Node predecessor(){};  //返回该节点的前一个节点

         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;
        }
    }//Node类


    private transient volatile Node head;

    private transient volatile Node tail;

        private volatile int state;   //   0表示未锁定   ,   1表示锁定

    private Node enq(final Node node) { //入队,第一个节点为空节点,即head所指向的节点
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                       t.next = node;
                    return t;
                }
            }
           }
    }

    private Node addWaiter(Node mode) { //mode ShARED or EXCLUSIVE
        Node node = new Node(Thread.currentThread(), mode);
           Node pred = tail;
           if (pred != null) {//队尾不为空,则添加新节点到队尾后面
            node.prev = pred;
                if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
                }
           }//尝试一次快速入队,入队失败则调用enque()循环入队
        enq(node);
           return node;
    }
    private void setHead(Node node) {//拿到资源后,将head指向该结点。所以head所指的标杆结点,就是当前获取到资源的那个结点或null。
        head = node;
        node.thread = null;
        node.prev = null;
    }
     //唤醒等待队列中下一个线程
     private void unparkSuccessor(Node node) {//这里,node一般为当前线程所在的结点。
        int ws = node.waitStatus;
        if (ws < 0)//置零当前线程所在的结点状态,允许失败。
            compareAndSetWaitStatus(node, ws, 0);
        Node s = node.next; //找到下一个需要唤醒的结点s
        if (s == null || s.waitStatus > 0) {//如果为空或已取消
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)//从这里可以看出,<=0的结点,都是还有效的结点。
                    s = t;
        }
        if (s != null)//唤醒
            LockSupport.unpark(s.thread);
    } 

    private void cancelAcquire(Node node) {//取消正在进行的尝试获取
        if (node == null)// Ignore if node doesn't exist
            return;
        node.thread = null;  //1. node不再关联到任何线程
        Node pred = node.prev;//2. 跳过被cancel的前继node,找到一个有效的前继节点pred
        while (pred.waitStatus > 0)
            node.prev = pred = pred.prev;
        Node predNext = pred.next;  
        node.waitStatus = Node.CANCELLED;//3. 将node的waitStatus置为CANCELLED

        if (node == tail && compareAndSetTail(node, pred)) {//4. 如果node是tail,更新tail为pred,并使pred.next指向null
            compareAndSetNext(pred, predNext, null);
        } 
        else      //5. 如果node既不是tail,又不是head的后继节点 则将node的前继节点的waitStatus置为SIGNAL
            {     //并使node的前继节点指向node的后继节点(相当于将node从队列中删掉了)    
                int ws;        
                if (pred != head &&
                    ((ws = pred.waitStatus) == Node.SIGNAL || (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) 
                    && pred.thread != null) {
                    
                    Node next = node.next;
                    if (next != null && next.waitStatus <= 0)
                        compareAndSetNext(pred, predNext, next);
                } else {//6. 如果node是head的后继节点,则直接唤醒node的后继节点
                    unparkSuccessor(node);
                }

                node.next = node; // help GC
            }
    }

    final boolean acquireQueued(final Node node, int arg) {//把已经追加到队列的线程节点(addWaiter方法返回值)进行阻塞,
            boolean failed = true;                        //但阻塞前又通过tryAccquire重试是否能获得锁,如果重试成功能则无需阻塞,直接返回
            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);
            }
        }


   private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {/*配合使用acquireQueued()for无限循环设置*/
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL)//首先检查前趋结点的waitStatus位,如果为SIGNAL,表示前趋结点会通知它,那么它可以放心大胆地挂起了
            return true;
        if (ws > 0) {//是一个被取消的结点向前遍历跳过被取消的结点,直到找到一个没有被取消的结点为止,
            do {     //将找到的这个结点作为它的前趋结点,后进入acquireQueued的无限循环
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);  //如果前继节点状态为非SIGNAL、非CANCELLED,则设置前继
        }                                                    //的状态为SIGNAL,返回false后进入acquireQueued的无限循环
        return false;//返回false表示线程不应该被挂起。
    }

    private final boolean parkAndCheckInterrupt() {//park and then check if interrupted
        LockSupport.park(this);
        return Thread.interrupted();
    }

    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) //调用Sync中的tryAcquire()
            selfInterrupt();
    }


    public final boolean release(int arg) {
        if (tryRelease(arg)) {//调用Sync中的tryRealse()
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

    public final boolean hasQueuedPredecessors() {//通过判断"当前线程"是不是在CLH队列的队首,来返回AQS中是不是有比“当                                                                               //前线程”等待更久的线程

        Node t = tail; // Read fields in reverse initialization order
        Node h = head;
        Node s;
        return  h != t  && ((s = h.next) == null || s.thread != Thread.currentThread());
    }

}

猜你喜欢

转载自blog.csdn.net/qmylzx/article/details/82846770