AbstractQueuedSynchronizer 源码理解

UnSafe类(原子操作):
/** 
* 比较obj的offset处内存位置中的值和期望的值,如果相同则更新。此更新是不可中断的。 
*  
* @param obj 需要更新的对象 
* @param offset obj中整型field的偏移量 
* @param expect 希望field中存在的值 
* @param update 如果期望值expect与field的当前值相同,设置filed的值为这个新值 
* @return 如果field的值被更改返回true 
*/  
public native boolean compareAndSwapInt(Object obj, long offset, int expect, int update);  
AbstractQueuedSynchronizer类:
     * <p>To enqueue into a CLH lock, you atomically splice it in as new
     * tail. To dequeue, you just set the head field.
     * <pre>
     *      + ------ +  prev + ----- +       + ----- +
     * head |      | <---- |     | <---- |     |  tail
     *      + ------ +       + ----- +       + ----- +
     * </pre>

  /**
     * Inserts node into queue, initializing if necessary. See picture above.
     * @param node the node to insert
     * @return node's predecessor
     */
    private Node enq( final Node node) {
        for (;;) {
            Node t = tail ;
            if (t == null ) { // Must initialize
                //如果头部为空,则更新,并赋值给tail
                if (compareAndSetHead( new Node()))
                    tail = head ;
            } else {
                // 让tail指向新插入的结点
                node. prev = t;
                if (compareAndSetTail(t, node)) {
                    t. next = node;
                    return t;
                }
            }
        }
    }

  /**
     * Creates and enqueues node for current thread and given mode.
     *
     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared 标明是否共享:  addWaiter(Node. EXCLUSIVE ) null 
addWaiter(Node. SHARED ); new Node();
     * @return the new node
     */
    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;
    }

你可能感兴趣的:(AbstractQueuedSynchronizer 源码理解)