ReentrantLock与AQS

ReentrantLock的Sync继承自AQS
  • Sync实现了nonfairTryAcquire 、tryRelease、isHeldExclusively,
    而TryAcquire和lock留给子类实现
abstract static class Sync extends AbstractQueuedSynchronizer {
    private static final long serialVersionUID = -5179523762034025860L;
    abstract void lock();
    final boolean nonfairTryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) {//当前可重入数为0,说明锁没有被其他线程获取
            if (compareAndSetState(0, acquires)) {//cas设置状态为重入数
                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) {//如果当前状态为0,说明锁没有被获取,设置独占线程为空,返回真
            free = true;
            setExclusiveOwnerThread(null);
        }
        setState(c);//如果重入数还没有变为0,就设置新的重入数返回
        return free;
    }
    protected final boolean isHeldExclusively() {
        // 在成为拥有者之前必须获取状态
        //当前线程已经是拥有者就不用再检查
        return getExclusiveOwnerThread() == Thread.currentThread();
    }
    final ConditionObject newCondition() {
        return new ConditionObject();
    }
    // Methods relayed from outer class
    final Thread getOwner() {
        return getState() == 0 ? null : getExclusiveOwnerThread();
    }
    final int getHoldCount() {
        return isHeldExclusively() ? getState() : 0;
    }
    final boolean isLocked() {
        return getState() != 0;
    }
    /**
     * Reconstitutes the instance from a stream (that is, deserializes it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();
        setState(0); // reset to unlocked state
    }
}
NonfairSync
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);
    }
}
FairSync
static final class FairSync extends Sync {
   private static final long serialVersionUID = -3000897897090466540L;
   final void lock() {
       acquire(1);
   }
   protected final boolean tryAcquire(int acquires) {
       final Thread current = Thread.currentThread();
       int c = getState();
       if (c == 0) {//当前没有其他线程竞争
           if (!hasQueuedPredecessors() //公平锁的实现查看当前线程是不是head的下一个节点
           //如果有等待的节点就返回true 没有等待的节点就返回false,进行下一步设置state
               compareAndSetState(0, acquires)) {
               setExclusiveOwnerThread(current);
               return true;
           }
       }
       //当前没有竞争,已经获取到锁直接设置state这是偏向锁的实现
       else if (current == getExclusiveOwnerThread()) {
           int nextc = c + acquires;
           if (nextc  0)
               throw new Error("Maximum lock count exceeded");
           setState(nextc);
           return true;
       }
       return false;
   }
}
  • hasQueuedPredecessors
public final boolean hasQueuedPredecessors() {
    Node t = tail; 
    Node h = head;
    Node s;
    //头结点等于尾节点返回false说明没有等待的节点
    //头结点不等于尾节点,查看头结点的下一个节点是不是空,
    //如果为空,说明有等待的节点,不为空就看这个节点是不是当前节点
    //如果是当前节点就返回false 说明没有等待的节点
    //如果不等于当前节点就返回true说明有等待的节点
    return h != t 
        ((s = h.next) == null || s.thread != Thread.currentThread());
}
最新回复(0)
/jishuP561KlA3qq8Bf2rpcwtDMw64Zm_2Bx3VbeZvgSzJeohCs_3D4794840
8 简首页