创建一个公平或者非公平的锁
如果tryAcquire()获取失败,则要执行addWaiter()向等待队列中添加一个独占模式的节点。
public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); }尝试加锁
final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { //如果线程状态为0 cas成1 if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } //如果状态不是0判断是否是当前线程 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; }这个方法的注释:创建一个入队node为当前线程,Node.EXCLUSIVE 是独占锁, Node.SHARED 是共享锁。 先找到等待队列的tail节点pred,如果pred!=null,就把当前线程添加到pred后面进入等待队列,如果不存在tail节点执行enq()
private Node addWaiter(Node mode) { Node node = new Node(Thread.currentThread(), mode); // Try the fast path of enq; backup to full enq on failure Node pred = tail; if (pred != null) { //新节点指向上一个节点 node.prev = pred; if (compareAndSetTail(pred, node)) { pred.next = node; return node; } } enq(node); return node; }这里进行了循环,如果此时存在了tail就执行同上一步骤的添加队尾操作,如果依然不存在,就把当前线程作为head结点。 插入节点后,调用acquireQueued()进行阻塞
private Node enq(final Node node) { for (;;) { Node t = tail; //判断头节点是不是null if (t == null) { // Must initialize //CAS设置头节点后再进入循环 if (compareAndSetHead(new Node())) //初始化时头尾节点为同一个 tail = head; } else { //新入队的节点上一个等于头节点 node.prev = t; //cas尾节点 if (compareAndSetTail(t, node)) { //上一个节点的下一个 t.next = node; return t; } } } }