当我阅读AbstractQueuedSynchronize
源代码时,关于方法
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;
}
}
}
}
我想知道为什么会有for循环,因为它可能像这样:
private Node enq(final Node node) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
}
node.prev = tail;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
这与并发有关系吗?
答案 0 :(得分:1)
该语法用于表示内部内容将无限次执行。它与:
while(true){..}
这意味着内部必须有一条语句可以中断此无限执行,可以是 break 或 return 。
在您的情况下,这是一个 return 语句,并且无限循环用于执行相同的任务,直到您达到满足 return 的条件为止。这仅在用于检查退出条件的状态中有进度/更改时才有效。在这种情况下,更改是通过跟随链接列表数据结构中的链接进行的。
答案 1 :(得分:0)
您的重写代码不是等效代码。在您的版本中,如果对compareAndSetHead(new Node())
的调用评估为false,则tail
在null
的位置仍为node.prev = tail;
包裹在for (;;) { ... }
中的原件将继续尝试,直到tail
不是{null
}。