java的AQS中enp没有同步代码块为啥是原子操作

先看一看enq()的代码

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;
                }
            }
        }
    }
看到这段代码稍微有点疑惑:
node.prev = t;
if (compareAndSetTail(t, node)) {
    t.next = node;
    return t;
}
为啥是原子操作?
compareAndSetTail(pred, node)是CAS原子操作我理解,那为啥if后面的语句也是原子的呢?执行t.next会不会指向错误的节点?
 
然后画了一下图就理解了,自己还是太菜了,这种简单的逻辑还思考了一段时间

 最后ThreadC的 t 指向ThreadB这个节点,而ThreadD的t指向ThreadC,当操作t.next=node的时候,他们并不会冲突。

 所以说这个场景中,cas后面的if语句并不会出现线程安全问题。



原文地址:https://www.cnblogs.com/yzdtofly/p/12911669.html