マルチスレッドと並行性の高い5-AQS

AQS

1、国家と国家の双方向リンクリストの共同作業。
ここに画像を挿入説明
図2に示すように、二重リンクリストノードステータスの正面図
3は、CAS + Volitile状態(ヘッドによって取得された現在のステータスは、テールキューの要素が追加される)
。4、volitile状態SETSTATE()とがあり、状態設定方法、修正されcompareAndState()[危険];
5、AQSメイン方法:。tryAcquire、tryRelease、tryAcquireShared、tryReleaseShared 、isHeldExclusively

//reentrantLock
final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();//获取state
            if (c == 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;
        }
//aqs
 private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);//mode,exclusive,Shared
        // 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)) {//cas自旋锁插入到链表最后一个节点
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }
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);
        }
    }

ロックを取得
ここに画像を挿入説明
リリースロック
解除がゼロの場合AQS、リリース- > tryRelease、解放状態-1による試み、状態を

公開された25元の記事 ウォンの賞賛0 ビュー582

おすすめ

転載: blog.csdn.net/RaymondCoder/article/details/105089642