为什么在 AbstractQueuedSynchronize enq(final Node node) 方法中有一个 for(;;)
why there's a for(;;) in AbstractQueuedSynchronize enq(final Node node) method
当我阅读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;
}
}
这和并发有关系吗?
语法是说里面的东西会被执行无限次。等同于:
while(true){..}
表示里面必须有一个语句来打破这个无限执行可以是break或者return .
在你的情况下,这是一个 return 语句,无限循环用于执行相同的任务,直到达到满足 [=17= 的条件]return。这仅在用于检查退出条件的状态中存在 progress/change 时才有效。在这种情况下,更改是通过链接列表数据结构中的链接进行的。
您重写的不是等效代码。在您的版本中,如果对 compareAndSetHead(new Node())
的调用计算结果为 false,tail
仍将是 null
在 node.prev = tail;
原来,包裹在for (;;) { ... }
中会不断尝试,直到tail
是非null
。
当我阅读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;
}
}
这和并发有关系吗?
语法是说里面的东西会被执行无限次。等同于:
while(true){..}
表示里面必须有一个语句来打破这个无限执行可以是break或者return .
在你的情况下,这是一个 return 语句,无限循环用于执行相同的任务,直到达到满足 [=17= 的条件]return。这仅在用于检查退出条件的状态中存在 progress/change 时才有效。在这种情况下,更改是通过链接列表数据结构中的链接进行的。
您重写的不是等效代码。在您的版本中,如果对 compareAndSetHead(new Node())
的调用计算结果为 false,tail
仍将是 null
在 node.prev = tail;
原来,包裹在for (;;) { ... }
中会不断尝试,直到tail
是非null
。