java多线程--java.util.concurrent.locks.AbstractQueuedSynchronizer解析(只包含多线程同步示例)

  jdk1.5和jdk1.6的多线程api有些不同,这里主要针对jdk1.5的多线程api的AbstractQueuedSynchronizer进行说明。jdk api中很多锁内部都实现并且使用了AbstractQueuedSynchronizer实现。
  AbstractQueuedSynchronizer实际上就是一个FIFO有状态双向队列。它声明了private volatile int state即AbstractQueuedSynchronizer的状态域,state属性用来表示这个同步器被请求了多少次(每请求一次state值加1)。它的结点用来保存在该AbstractQueuedSynchronizer上请求的线程,请求的模式(共享模式还是互斥模式),和线程的状态(等待唤醒,处于condition的等待队列中,已被取消(中断)) 以下是AbstractQueuedSynchronizer结点的内部实现:
   static final class Node {
        /** waitStatus value to indicate thread has cancelled */
        static final int CANCELLED =  1;
        /** waitStatus value to indicate successor's thread needs unparking */
        static final int SIGNAL    = -1;
        /** waitStatus value to indicate thread is waiting on condition */
        static final int CONDITION = -2;
        /** Marker to indicate a node is waiting in shared mode */
        static final Node SHARED = new Node();
        /** Marker to indicate a node is waiting in exclusive mode */
        static final Node EXCLUSIVE = null;

        /**
         * Status field, taking on only the values:
         *   SIGNAL:     The successor of this node is (or will soon be)
         *               blocked (via park), so the current node must
         *               unpark its successor when it releases or
         *               cancels. To avoid races, acquire methods must
         *               first indicate they need a signal,
         *               then retry the atomic acquire, and then,
         *               on failure, block.
         *   CANCELLED:  This node is cancelled due to timeout or interrupt.
         *               Nodes never leave this state. In particular,
         *               a thread with cancelled node never again blocks.
         *   CONDITION:  This node is currently on a condition queue.
         *               It will not be used as a sync queue node until
         *               transferred. (Use of this value here
         *               has nothing to do with the other uses
         *               of the field, but simplifies mechanics.)
         *   0:          None of the above
         *
         * The values are arranged numerically to simplify use.
         * Non-negative values mean that a node doesn't need to
         * signal. So, most code doesn't need to check for particular
         * values, just for sign.
         *
         * The field is initialized to 0 for normal sync nodes, and
         * CONDITION for condition nodes.  It is modified only using
         * CAS.
         */
        volatile int waitStatus;

        /**
         * Link to predecessor node that current node/thread relies on
         * for checking waitStatus. Assigned during enqueing, and nulled
         * out (for sake of GC) only upon dequeuing.  Also, upon
         * cancellation of a predecessor, we short-circuit while
         * finding a non-cancelled one, which will always exist
         * because the head node is never cancelled: A node becomes
         * head only as a result of successful acquire. A
         * cancelled thread never succeeds in acquiring, and a thread only
         * cancels itself, not any other node.
         */
        volatile Node prev;

        /**
         * Link to the successor node that the current node/thread
         * unparks upon release. Assigned once during enqueuing, and
         * nulled out (for sake of GC) when no longer needed.  Upon
         * cancellation, we cannot adjust this field, but can notice
         * status and bypass the node if cancelled.  The enq operation
         * does not assign next field of a predecessor until after
         * attachment, so seeing a null next field does not
         * necessarily mean that node is at end of queue. However, if
         * a next field appears to be null, we can scan prev's from
         * the tail to double-check.
         */
        volatile Node next;

        /**
         * The thread that enqueued this node.  Initialized on
         * construction and nulled out after use.
         */
        volatile Thread thread;

        /**
         * Link to next node waiting on condition, or the special
         * value SHARED.  Because condition queues are accessed only
         * when holding in exclusive mode, we just need a simple
         * linked queue to hold nodes while they are waiting on
         * conditions. They are then transferred to the queue to
         * re-acquire. And because conditions can only be exclusive,
         * we save a field by using special value to indicate shared
         * mode.
         */
        Node nextWaiter;

        /**
         * Returns true if node is waiting in shared mode
         */
        final boolean isShared() {
            return nextWaiter == SHARED;
        }

        /**
         * Returns previous node, or throws NullPointerException if
         * null.  Use when predecessor cannot be null.
         * @return the predecessor of this node
         */
        final Node predecessor() throws NullPointerException {
            Node p = prev;
            if (p == null)
                throw new NullPointerException();
            else
                return p;
        }

        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;
        }
    }
以下将以Lock的lock方法为例(Lock接口的主要实现类为ReentrantLock),来看下java concurrent api是如何利用java语法而不是java语义来实现多线程FIFO同步的。ReentrantLock在内部实现了两个AbstractQueuedSynchronizer,即FairSync和NonfairSync,它们都实现了lock()方法。现以FairSync的lock实现为例。
    1.在获取lock对象的锁时即调用lock对象的lock方法时,首先会调用该lock对象内部同步器e.g.FairSync的tryAcquire方法,试着获取一个锁。
    2.如果第一步操作成功且当前线程是第一个获取到该锁的线程则把当前线程设置为该锁的所有者(owner),并设置同步器的状态(即锁请求的次数);如果不是第一个获取到该锁的线程则设置同步器的状态
    3.如果第一步操作失败则先把当前线程插入到FIFO队列中(通过AbstractQueuedSynchronizer的addWaiter方法)。调用同步框架同步器基类AbstractQueuedSynchronizer的acquireQueued方法来顺序(FIFO)的获取该锁。具体的:
      i.如果当前线程是FIFO队列的第一个结点(第一个结点非头结点,该FIFO队列头结点为DUMMY结点,不是有效结点),则再次调用同步器实现类的tryAcquire方法来获取该锁。获取成功则设置整个FIFO队列的头结点,释放以前的头结点。
     ii.如果当前线程不是FIFO队列的第一个结点,则调用同步框架同步器基类AbstractQueuedSynchronizer的shouldParkAfterFailedAcquire方法来判断是否当前线程应该被挂起(具体逻辑参看shouldParkAfterFailedAcquire方法,它是根据FIFO队列当前线程所处结点的前一个结点的状态来判断的。如果前一个结点的等待状态waitStatus<0则表示前一个结点所包含的线程还没有获取到锁,还在等待,那么当前线程就可以安心的等待了,该方法就返回true,表明当前线程应该park;如果前一个结点的等待状态waitStatus>0则表示前一个结点的状态为CANCELLED状态了,则把该结点之前的所有为CANCELLED状态的结点从FIFO队列中去除,该方法就返回false,表明当前线程不应该park,应该继续执行;如果前一个结点状态waitStatus=0则把它的状态设置为SIGNAL状态,即-1,该方法就返回false,表明当前线程不应该park,应该继续执行)
     iii.根据第二步的结果如果当前线程需要park,则park当前线程;否则继续执行第一步。
      步骤i,ii,iii这个循环使得当前线程所处的FIFO队列之前的所有结点都获取到了锁之后才能获取到锁,否则当前线程就被park。
    具体的实现逻辑:
          /**
     * 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) {
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } catch (RuntimeException ex) {
            cancelAcquire(node);
            throw ex;
        }
    }
    java concurrent框架通过CAS和底层的LockSupport支持,通过java语法的方式而不是java语义的方式使java多线程同步,异步操作更加灵活。jdk实现提供了以AbstractQueuedSynchronizer为核心的多线程框架,我们可以更方便的使用java多线程了。

你可能感兴趣的:(java,jdk,多线程,thread,框架)