• JUC AQS ReentrantLock源码分析


      为了了解java并发包下的  ReentrantLock 可重入锁 和 AbstractQueuedSynchronizer 抽象队列同步器,我自己创建了这两个类,改一下类名,把他们的代码贴过来,再删除英文注释,一步步的分析,再贴上自己的中文理解。
    然后我发现 BacAQS只有940行,BacReentrantLock 只有230行,然后攻克她。Bac 是我起的英文名,高大上的寓意是 大数据BigData ,Ai人工智能,CloudComputing云计算。读音:巴西。不是喜欢足球,是自己胖得像球。。。
      直接上代码,后续会慢慢解读,补充中文注释。你也可以按这个方法,一起学习哦。

    可重入锁:
    
    
    package www.itbac.com;

    import java.util.Collection;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    //可重入锁
    public class BacReentrantLock implements Lock, java.io.Serializable {
    private static final long serialVersionUID = 9115702519755564786L;

    private final Sync sync;
    //FairSync 公平同步,公平锁。
    //NonfairSync 非公平同步,非公平锁
    abstract static class Sync extends BacAQS {
    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) {
    if (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;
    }
    //尝试释放
    @Override
    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;
    }

    @Override
    protected final boolean isHeldExclusively() {
    return getExclusiveOwnerThread() == Thread.currentThread();
    }

    final ConditionObject newCondition() {
    return new ConditionObject();
    }


    final Thread getOwner() {
    return getState() == 0 ? null : getExclusiveOwnerThread();
    }

    final int getHoldCount() {
    return isHeldExclusively() ? getState() : 0;
    }

    final boolean isLocked() {
    return getState() != 0;
    }

    private void readObject(java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {
    s.defaultReadObject();
    setState(0);
    }
    }
    //非公平锁
    static final class NonfairSync extends Sync {
    private static final long serialVersionUID = 7316153563782823691L;

    @Override
    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;

    @Override
    final void lock() {
    acquire(1);
    }
    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 BacReentrantLock() {
    sync = new NonfairSync();
    }
    //有参构造,可选择 公平锁 或 非公平锁
    public BacReentrantLock(boolean fair) {
    sync = fair ? new FairSync() : new NonfairSync();
    }
    //获取锁
    @Override
    public void lock() {
    sync.lock();
    }
    //线程中断
    @Override
    public void lockInterruptibly() throws InterruptedException {
    sync.acquireInterruptibly(1);
    }
    //尝试获取锁
    @Override
    public boolean tryLock() {
    return sync.nonfairTryAcquire(1);
    }
    //尝试获取锁
    @Override
    public boolean tryLock(long timeout, TimeUnit unit)
    throws InterruptedException {
    return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }
    //释放锁
    @Override
    public void unlock() {
    sync.release(1);
    }

    @Override
    public Condition newCondition() {
    return sync.newCondition();
    }

    public int getHoldCount() {
    return sync.getHoldCount();
    }

    public boolean isHeldByCurrentThread() {
    return sync.isHeldExclusively();
    }

    public boolean isLocked() {
    return sync.isLocked();
    }

    public final boolean isFair() {
    return sync instanceof FairSync;
    }

    protected Thread getOwner() {
    return sync.getOwner();
    }

    public final boolean hasQueuedThreads() {
    return sync.hasQueuedThreads();
    }

    public final boolean hasQueuedThread(Thread thread) {
    return sync.isQueued(thread);
    }

    public final int getQueueLength() {
    return sync.getQueueLength();
    }

    protected Collection<Thread> getQueuedThreads() {
    return sync.getQueuedThreads();
    }

    public boolean hasWaiters(Condition condition) {
    if (condition == null)
    throw new NullPointerException();
    if (!(condition instanceof BacAQS.ConditionObject))
    throw new IllegalArgumentException("not owner");
    return sync.hasWaiters((BacAQS.ConditionObject)condition);
    }

    public int getWaitQueueLength(Condition condition) {
    if (condition == null)
    throw new NullPointerException();
    if (!(condition instanceof BacAQS.ConditionObject))
    throw new IllegalArgumentException("not owner");
    return sync.getWaitQueueLength((BacAQS.ConditionObject)condition);
    }

    protected Collection<Thread> getWaitingThreads(Condition condition) {
    if (condition == null)
    throw new NullPointerException();
    if (!(condition instanceof BacAQS.ConditionObject))
    throw new IllegalArgumentException("not owner");
    return sync.getWaitingThreads((BacAQS.ConditionObject)condition);
    }

    @Override
    public String toString() {
    Thread o = sync.getOwner();
    return super.toString() + ((o == null) ?
    "[Unlocked]" :
    "[Locked by thread " + o.getName() + "]");
    }
    }
     

    抽象队列同步器:

    
    
    package www.itbac.com;

    import sun.misc.Unsafe;

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Date;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.locks.*;

    //AbstractQueuedSynchronizer 抽象队列器
    public abstract class BacAQS extends AbstractOwnableSynchronizer
    implements java.io.Serializable{
    private static final long serialVersionUID = -8891887006214362370L;
    protected BacAQS() { }
    //Node节点
    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;
    static final int PROPAGATE = -3;
    //volatile 关键字修饰变量,让变量具有 可见性,是指线程之间的可见性,一个线程修改的状态对另一个线程是可见的。
    //等待状态
    volatile int waitStatus;
    //上一个节点
    volatile Node prev;
    //下一个节点
    volatile Node next;
    //自己节点存储自己的线程
    volatile Thread thread;
    //下一个服务员
    Node nextWaiter;

    final boolean isShared() {
    return nextWaiter == SHARED;
    }
    //获取当前节点的上一个节点。
    final Node predecessor() throws NullPointerException {
    Node p = prev;
    if (p == null)
    throw new NullPointerException();
    else
    return p;
    }
    //无参构造
    Node() {
    }
    //有参构造
    Node(Thread thread, Node mode) {
    this.nextWaiter = mode;
    this.thread = thread;
    }
    //有参构造
    Node(Thread thread, int waitStatus) {
    this.waitStatus = waitStatus;
    this.thread = thread;
    }
    }
    //用transient关键字标记的成员变量不参与序列化过程
    //队列的 头 节点
    private transient volatile Node head;
    //队列的 尾 节点
    private transient volatile Node tail;
    //锁的状态: 初始状态0 ,加锁成功则为1 ,重入 +1 ,解锁则恢复为 0 。
    private volatile int state;
    //获取状态
    protected final int getState() {
    return state;
    }
    //设置状态
    protected final void setState(int newState) {
    state = newState;
    }

    protected final boolean compareAndSetState(int expect, int update) {
    return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }

    static final long spinForTimeoutThreshold = 1000L;

    private Node enq(final Node node) {
    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) {
    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;
    }
    }
    enq(node);
    return node;
    }

    private void setHead(Node node) {
    head = node;
    node.thread = null;
    node.prev = null;
    }

    private void unparkSuccessor(Node node) {
    int ws = node.waitStatus;
    if (ws < 0)
    compareAndSetWaitStatus(node, ws, 0);

    Node s = node.next;
    if (s == null || s.waitStatus > 0) {
    s = null;
    for (Node t = tail; t != null && t != node; t = t.prev)
    if (t.waitStatus <= 0)
    s = t;
    }
    if (s != null)
    LockSupport.unpark(s.thread);
    }

    private void doReleaseShared() {
    for (;;) {
    Node h = head;
    if (h != null && h != tail) {
    int ws = h.waitStatus;
    if (ws == Node.SIGNAL) {
    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
    continue; // loop to recheck cases
    unparkSuccessor(h);
    }
    else if (ws == 0 &&
    !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
    continue; // loop on failed CAS
    }
    if (h == head) // loop if head changed
    break;
    }
    }

    private void setHeadAndPropagate(Node node, int propagate) {
    Node h = head; // Record old head for check below
    setHead(node);
    if (propagate > 0 || h == null || h.waitStatus < 0 ||
    (h = head) == null || h.waitStatus < 0) {
    Node s = node.next;
    if (s == null || s.isShared())
    doReleaseShared();
    }
    }

    private void cancelAcquire(Node node) {
    if (node == null)
    return;

    node.thread = null;

    Node pred = node.prev;
    while (pred.waitStatus > 0)
    node.prev = pred = pred.prev;

    Node predNext = pred.next;

    node.waitStatus = Node.CANCELLED;

    if (node == tail && compareAndSetTail(node, pred)) {
    compareAndSetNext(pred, predNext, null);
    } else {
    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 {
    unparkSuccessor(node);
    }

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

    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
    int ws = pred.waitStatus;
    if (ws == Node.SIGNAL)
    return true;
    if (ws > 0) {
    do {
    node.prev = pred = pred.prev;
    } while (pred.waitStatus > 0);
    pred.next = node;
    } else {
    compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
    }
    return false;
    }

    static void selfInterrupt() {
    Thread.currentThread().interrupt();
    }

    private final boolean parkAndCheckInterrupt() {
    LockSupport.park(this);
    return Thread.interrupted();
    }

    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);
    }
    }

    private void doAcquireInterruptibly(int arg)
    throws InterruptedException {
    final Node node = addWaiter(Node.EXCLUSIVE);
    boolean failed = true;
    try {
    for (;;) {
    final Node p = node.predecessor();
    if (p == head && tryAcquire(arg)) {
    setHead(node);
    p.next = null; // help GC
    failed = false;
    return;
    }
    if (shouldParkAfterFailedAcquire(p, node) &&
    parkAndCheckInterrupt())
    throw new InterruptedException();
    }
    } finally {
    if (failed)
    cancelAcquire(node);
    }
    }

    private boolean doAcquireNanos(int arg, long nanosTimeout)
    throws InterruptedException {
    if (nanosTimeout <= 0L)
    return false;
    final long deadline = System.nanoTime() + nanosTimeout;
    final Node node = addWaiter(Node.EXCLUSIVE);
    boolean failed = true;
    try {
    for (;;) {
    final Node p = node.predecessor();
    if (p == head && tryAcquire(arg)) {
    setHead(node);
    p.next = null; // help GC
    failed = false;
    return true;
    }
    nanosTimeout = deadline - System.nanoTime();
    if (nanosTimeout <= 0L)
    return false;
    if (shouldParkAfterFailedAcquire(p, node) &&
    nanosTimeout > spinForTimeoutThreshold)
    LockSupport.parkNanos(this, nanosTimeout);
    if (Thread.interrupted())
    throw new InterruptedException();
    }
    } finally {
    if (failed)
    cancelAcquire(node);
    }
    }

    private void doAcquireShared(int arg) {
    final Node node = addWaiter(Node.SHARED);
    boolean failed = true;
    try {
    boolean interrupted = false;
    for (;;) {
    final Node p = node.predecessor();
    if (p == head) {
    int r = tryAcquireShared(arg);
    if (r >= 0) {
    setHeadAndPropagate(node, r);
    p.next = null; // help GC
    if (interrupted)
    selfInterrupt();
    failed = false;
    return;
    }
    }
    if (shouldParkAfterFailedAcquire(p, node) &&
    parkAndCheckInterrupt())
    interrupted = true;
    }
    } finally {
    if (failed)
    cancelAcquire(node);
    }
    }

    private void doAcquireSharedInterruptibly(int arg)
    throws InterruptedException {
    final Node node = addWaiter(Node.SHARED);
    boolean failed = true;
    try {
    for (;;) {
    final Node p = node.predecessor();
    if (p == head) {
    int r = tryAcquireShared(arg);
    if (r >= 0) {
    setHeadAndPropagate(node, r);
    p.next = null; // help GC
    failed = false;
    return;
    }
    }
    if (shouldParkAfterFailedAcquire(p, node) &&
    parkAndCheckInterrupt())
    throw new InterruptedException();
    }
    } finally {
    if (failed)
    cancelAcquire(node);
    }
    }

    private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
    throws InterruptedException {
    if (nanosTimeout <= 0L)
    return false;
    final long deadline = System.nanoTime() + nanosTimeout;
    final Node node = addWaiter(Node.SHARED);
    boolean failed = true;
    try {
    for (;;) {
    final Node p = node.predecessor();
    if (p == head) {
    int r = tryAcquireShared(arg);
    if (r >= 0) {
    setHeadAndPropagate(node, r);
    p.next = null; // help GC
    failed = false;
    return true;
    }
    }
    nanosTimeout = deadline - System.nanoTime();
    if (nanosTimeout <= 0L)
    return false;
    if (shouldParkAfterFailedAcquire(p, node) &&
    nanosTimeout > spinForTimeoutThreshold)
    LockSupport.parkNanos(this, nanosTimeout);
    if (Thread.interrupted())
    throw new InterruptedException();
    }
    } finally {
    if (failed)
    cancelAcquire(node);
    }
    }

    protected boolean tryAcquire(int arg) {
    throw new UnsupportedOperationException();
    }

    protected boolean tryRelease(int arg) {
    throw new UnsupportedOperationException();
    }

    protected int tryAcquireShared(int arg) {
    throw new UnsupportedOperationException();
    }

    protected boolean tryReleaseShared(int arg) {
    throw new UnsupportedOperationException();
    }

    protected boolean isHeldExclusively() {
    throw new UnsupportedOperationException();
    }

    public final void acquire(int arg) {
    if (!tryAcquire(arg) &&
    acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
    selfInterrupt();
    }
    public final void acquireInterruptibly(int arg)
    throws InterruptedException {
    if (Thread.interrupted())
    throw new InterruptedException();
    if (!tryAcquire(arg))
    doAcquireInterruptibly(arg);
    }
    public final boolean tryAcquireNanos(int arg, long nanosTimeout)
    throws InterruptedException {
    if (Thread.interrupted())
    throw new InterruptedException();
    return tryAcquire(arg) ||
    doAcquireNanos(arg, nanosTimeout);
    }
    public final boolean release(int arg) {
    if (tryRelease(arg)) {
    Node h = head;
    if (h != null && h.waitStatus != 0)
    unparkSuccessor(h);
    return true;
    }
    return false;
    }
    public final void acquireShared(int arg) {
    if (tryAcquireShared(arg) < 0)
    doAcquireShared(arg);
    }
    public final void acquireSharedInterruptibly(int arg)
    throws InterruptedException {
    if (Thread.interrupted())
    throw new InterruptedException();
    if (tryAcquireShared(arg) < 0)
    doAcquireSharedInterruptibly(arg);
    }

    public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
    throws InterruptedException {
    if (Thread.interrupted())
    throw new InterruptedException();
    return tryAcquireShared(arg) >= 0 ||
    doAcquireSharedNanos(arg, nanosTimeout);
    }

    public final boolean releaseShared(int arg) {
    if (tryReleaseShared(arg)) {
    doReleaseShared();
    return true;
    }
    return false;
    }


    public final boolean hasQueuedThreads() {
    return head != tail;
    }

    public final boolean hasContended() {
    return head != null;
    }

    public final Thread getFirstQueuedThread() {
    return (head == tail) ? null : fullGetFirstQueuedThread();
    }

    private Thread fullGetFirstQueuedThread() {
    Node h, s;
    Thread st;
    if (((h = head) != null && (s = h.next) != null &&
    s.prev == head && (st = s.thread) != null) ||
    ((h = head) != null && (s = h.next) != null &&
    s.prev == head && (st = s.thread) != null))
    return st;


    Node t = tail;
    Thread firstThread = null;
    while (t != null && t != head) {
    Thread tt = t.thread;
    if (tt != null)
    firstThread = tt;
    t = t.prev;
    }
    return firstThread;
    }

    public final boolean isQueued(Thread thread) {
    if (thread == null)
    throw new NullPointerException();
    for (Node p = tail; p != null; p = p.prev)
    if (p.thread == thread)
    return true;
    return false;
    }

    final boolean apparentlyFirstQueuedIsExclusive() {
    Node h, s;
    return (h = head) != null &&
    (s = h.next) != null &&
    !s.isShared() &&
    s.thread != null;
    }

    public final boolean hasQueuedPredecessors() {
    Node t = tail;
    Node h = head;
    Node s;
    return h != t &&
    ((s = h.next) == null || s.thread != Thread.currentThread());
    }

    public final int getQueueLength() {
    int n = 0;
    for (Node p = tail; p != null; p = p.prev) {
    if (p.thread != null)
    ++n;
    }
    return n;
    }
    public final Collection<Thread> getQueuedThreads() {
    ArrayList<Thread> list = new ArrayList<Thread>();
    for (Node p = tail; p != null; p = p.prev) {
    Thread t = p.thread;
    if (t != null)
    list.add(t);
    }
    return list;
    }

    public final Collection<Thread> getExclusiveQueuedThreads() {
    ArrayList<Thread> list = new ArrayList<Thread>();
    for (Node p = tail; p != null; p = p.prev) {
    if (!p.isShared()) {
    Thread t = p.thread;
    if (t != null)
    list.add(t);
    }
    }
    return list;
    }
    public final Collection<Thread> getSharedQueuedThreads() {
    ArrayList<Thread> list = new ArrayList<Thread>();
    for (Node p = tail; p != null; p = p.prev) {
    if (p.isShared()) {
    Thread t = p.thread;
    if (t != null)
    list.add(t);
    }
    }
    return list;
    }
    public String toString() {
    int s = getState();
    String q = hasQueuedThreads() ? "non" : "";
    return super.toString() +
    "[State = " + s + ", " + q + "empty queue]";
    }
    final boolean isOnSyncQueue(Node node) {
    if (node.waitStatus == Node.CONDITION || node.prev == null)
    return false;
    if (node.next != null) // If has successor, it must be on queue
    return true;
    return findNodeFromTail(node);
    }


    private boolean findNodeFromTail(Node node) {
    Node t = tail;
    for (;;) {
    if (t == node)
    return true;
    if (t == null)
    return false;
    t = t.prev;
    }
    }

    final boolean transferForSignal(Node node) {
    if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
    return false;

    Node p = enq(node);
    int ws = p.waitStatus;
    if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
    LockSupport.unpark(node.thread);
    return true;
    }

    final boolean transferAfterCancelledWait(Node node) {
    if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
    enq(node);
    return true;
    }
    while (!isOnSyncQueue(node))
    Thread.yield();
    return false;
    }

    final int fullyRelease(Node node) {
    boolean failed = true;
    try {
    int savedState = getState();
    if (release(savedState)) {
    failed = false;
    return savedState;
    } else {
    throw new IllegalMonitorStateException();
    }
    } finally {
    if (failed)
    node.waitStatus = Node.CANCELLED;
    }
    }

    public final boolean owns(ConditionObject condition) {
    return condition.isOwnedBy(this);
    }

    public final boolean hasWaiters(ConditionObject condition) {
    if (!owns(condition))
    throw new IllegalArgumentException("Not owner");
    return condition.hasWaiters();
    }

    public final int getWaitQueueLength(ConditionObject condition) {
    if (!owns(condition))
    throw new IllegalArgumentException("Not owner");
    return condition.getWaitQueueLength();
    }

    public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
    if (!owns(condition))
    throw new IllegalArgumentException("Not owner");
    return condition.getWaitingThreads();
    }

    public class ConditionObject implements Condition, java.io.Serializable {
    private static final long serialVersionUID = 1173984872572414699L;
    private transient Node firstWaiter;
    private transient Node lastWaiter;

    public ConditionObject() { }

    private Node addConditionWaiter() {
    Node t = lastWaiter;
    if (t != null && t.waitStatus != Node.CONDITION) {
    unlinkCancelledWaiters();
    t = lastWaiter;
    }
    Node node = new Node(Thread.currentThread(), Node.CONDITION);
    if (t == null)
    firstWaiter = node;
    else
    t.nextWaiter = node;
    lastWaiter = node;
    return node;
    }

    private void doSignal(Node first) {
    do {
    if ( (firstWaiter = first.nextWaiter) == null)
    lastWaiter = null;
    first.nextWaiter = null;
    } while (!transferForSignal(first) &&
    (first = firstWaiter) != null);
    }

    private void doSignalAll(Node first) {
    lastWaiter = firstWaiter = null;
    do {
    Node next = first.nextWaiter;
    first.nextWaiter = null;
    transferForSignal(first);
    first = next;
    } while (first != null);
    }

    private void unlinkCancelledWaiters() {
    Node t = firstWaiter;
    Node trail = null;
    while (t != null) {
    Node next = t.nextWaiter;
    if (t.waitStatus != Node.CONDITION) {
    t.nextWaiter = null;
    if (trail == null)
    firstWaiter = next;
    else
    trail.nextWaiter = next;
    if (next == null)
    lastWaiter = trail;
    }
    else
    trail = t;
    t = next;
    }
    }

    public final void signal() {
    if (!isHeldExclusively())
    throw new IllegalMonitorStateException();
    Node first = firstWaiter;
    if (first != null)
    doSignal(first);
    }

    public final void signalAll() {
    if (!isHeldExclusively())
    throw new IllegalMonitorStateException();
    Node first = firstWaiter;
    if (first != null)
    doSignalAll(first);
    }

    public final void awaitUninterruptibly() {
    Node node = addConditionWaiter();
    int savedState = fullyRelease(node);
    boolean interrupted = false;
    while (!isOnSyncQueue(node)) {
    LockSupport.park(this);
    if (Thread.interrupted())
    interrupted = true;
    }
    if (acquireQueued(node, savedState) || interrupted)
    selfInterrupt();
    }


    private static final int REINTERRUPT = 1;
    private static final int THROW_IE = -1;

    private int checkInterruptWhileWaiting(Node node) {
    return Thread.interrupted() ?
    (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
    0;
    }

    private void reportInterruptAfterWait(int interruptMode)
    throws InterruptedException {
    if (interruptMode == THROW_IE)
    throw new InterruptedException();
    else if (interruptMode == REINTERRUPT)
    selfInterrupt();
    }

    public final void await() throws InterruptedException {
    if (Thread.interrupted())
    throw new InterruptedException();
    Node node = addConditionWaiter();
    int savedState = fullyRelease(node);
    int interruptMode = 0;
    while (!isOnSyncQueue(node)) {
    LockSupport.park(this);
    if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
    break;
    }
    if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
    interruptMode = REINTERRUPT;
    if (node.nextWaiter != null)
    unlinkCancelledWaiters();
    if (interruptMode != 0)
    reportInterruptAfterWait(interruptMode);
    }

    public final long awaitNanos(long nanosTimeout)
    throws InterruptedException {
    if (Thread.interrupted())
    throw new InterruptedException();
    Node node = addConditionWaiter();
    int savedState = fullyRelease(node);
    final long deadline = System.nanoTime() + nanosTimeout;
    int interruptMode = 0;
    while (!isOnSyncQueue(node)) {
    if (nanosTimeout <= 0L) {
    transferAfterCancelledWait(node);
    break;
    }
    if (nanosTimeout >= spinForTimeoutThreshold)
    LockSupport.parkNanos(this, nanosTimeout);
    if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
    break;
    nanosTimeout = deadline - System.nanoTime();
    }
    if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
    interruptMode = REINTERRUPT;
    if (node.nextWaiter != null)
    unlinkCancelledWaiters();
    if (interruptMode != 0)
    reportInterruptAfterWait(interruptMode);
    return deadline - System.nanoTime();
    }

    @Override
    public final boolean awaitUntil(Date deadline)
    throws InterruptedException {
    long abstime = deadline.getTime();
    if (Thread.interrupted())
    throw new InterruptedException();
    Node node = addConditionWaiter();
    int savedState = fullyRelease(node);
    boolean timedout = false;
    int interruptMode = 0;
    while (!isOnSyncQueue(node)) {
    if (System.currentTimeMillis() > abstime) {
    timedout = transferAfterCancelledWait(node);
    break;
    }
    LockSupport.parkUntil(this, abstime);
    if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
    break;
    }
    if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
    interruptMode = REINTERRUPT;
    if (node.nextWaiter != null)
    unlinkCancelledWaiters();
    if (interruptMode != 0)
    reportInterruptAfterWait(interruptMode);
    return !timedout;
    }

    @Override
    public final boolean await(long time, TimeUnit unit)
    throws InterruptedException {
    long nanosTimeout = unit.toNanos(time);
    if (Thread.interrupted())
    throw new InterruptedException();
    Node node = addConditionWaiter();
    int savedState = fullyRelease(node);
    final long deadline = System.nanoTime() + nanosTimeout;
    boolean timedout = false;
    int interruptMode = 0;
    while (!isOnSyncQueue(node)) {
    if (nanosTimeout <= 0L) {
    timedout = transferAfterCancelledWait(node);
    break;
    }
    if (nanosTimeout >= spinForTimeoutThreshold)
    LockSupport.parkNanos(this, nanosTimeout);
    if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
    break;
    nanosTimeout = deadline - System.nanoTime();
    }
    if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
    interruptMode = REINTERRUPT;
    if (node.nextWaiter != null)
    unlinkCancelledWaiters();
    if (interruptMode != 0)
    reportInterruptAfterWait(interruptMode);
    return !timedout;
    }

    final boolean isOwnedBy(BacAQS sync) {
    return sync == BacAQS.this;
    }

    protected final boolean hasWaiters() {
    if (!isHeldExclusively())
    throw new IllegalMonitorStateException();
    for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
    if (w.waitStatus == Node.CONDITION)
    return true;
    }
    return false;
    }

    protected final int getWaitQueueLength() {
    if (!isHeldExclusively())
    throw new IllegalMonitorStateException();
    int n = 0;
    for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
    if (w.waitStatus == Node.CONDITION)
    ++n;
    }
    return n;
    }

    protected final Collection<Thread> getWaitingThreads() {
    if (!isHeldExclusively())
    throw new IllegalMonitorStateException();
    ArrayList<Thread> list = new ArrayList<Thread>();
    for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
    if (w.waitStatus == Node.CONDITION) {
    Thread t = w.thread;
    if (t != null)
    list.add(t);
    }
    }
    return list;
    }
    }
    // 反射获取 sun公司定义操作native本地方法的不安全类Unsafe。
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long stateOffset;
    private static final long headOffset;
    private static final long tailOffset;
    private static final long waitStatusOffset;
    private static final long nextOffset;

    static {
    try {
    //获取属性state 在类 BacAQS 的内存地址偏移量
    stateOffset = unsafe.objectFieldOffset
    (BacAQS.class.getDeclaredField("state"));
    headOffset = unsafe.objectFieldOffset
    (BacAQS.class.getDeclaredField("head"));
    tailOffset = unsafe.objectFieldOffset
    (BacAQS.class.getDeclaredField("tail"));
    waitStatusOffset = unsafe.objectFieldOffset
    (Node.class.getDeclaredField("waitStatus"));
    nextOffset = unsafe.objectFieldOffset
    (Node.class.getDeclaredField("next"));

    } catch (Exception ex) { throw new Error(ex); }
    }
    //native原子操作,比较和替换 AQS队列的 头 节点
    private final boolean compareAndSetHead(Node update) {
    return unsafe.compareAndSwapObject(this, headOffset, null, update);
    }
    //native原子操作,比较和替换 AQS队列的 尾 节点
    private final boolean compareAndSetTail(Node expect, Node update) {
    return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
    }
    //native原子操作,比较和替换 节点的 等待状态
    private static final boolean compareAndSetWaitStatus(Node node,
    int expect,
    int update) {
    return unsafe.compareAndSwapInt(node, waitStatusOffset,
    expect, update);
    }
    //native原子操作,比较和替换 节点的 下一个节点。
    private static final boolean compareAndSetNext(Node node,
    Node expect,
    Node update) {
    return unsafe.compareAndSwapObject(node, nextOffset, expect, update);
    }
    }
    
    

    来一张示意图:

    哈,分享就先到这了。

    说点励志的话: 目标阿里P6,只去更强的公司,不为更高的工资。让自己变强,成为技术大牛。加油



  • 相关阅读:
    上海 政府性 常用网站
    linux 如何显示一个文件的某几行(中间几行)
    oracle 替换其中部分内容
    notepad++ 开始和结尾
    ll -d
    Mongodb总结3-稍微封装一下
    Mongodb总结3-稍微封装一下
    Mongodb总结2-Java版本的HelloWorld-CRUD例子
    Mongodb总结2-Java版本的HelloWorld-CRUD例子
    Mongodb总结1-启动和Shell脚本
  • 原文地址:https://www.cnblogs.com/itbac/p/11404351.html
Copyright © 2020-2023  润新知