2 回答

TA貢獻1801條經(jīng)驗 獲得超16個贊
就一個線程在處理的話肯定不會走casTail這句,如果有多個線程呢?
public boolean offer(E e) {
checkNotNull(e);
final Node<E> newNode = new Node<E>(e);
for (Node<E> t = tail, p = t;;) {
//如果2個線程到這里,一個先把流程走完了
//第二個線程的q開始執(zhí)行的時候已經(jīng)不是null了
//所以會走else的分支,修改了p和t的關(guān)系
Node<E> q = p.next;
if (q == null) {
// p is last node
if (p.casNext(null, newNode)) {
// Successful CAS is the linearization point
// for e to become an element of this queue,
// and for newNode to become "live".
if (p != t) // hop two nodes at a time
casTail(t, newNode); // Failure is OK.
return true;
}
// Lost CAS race to another thread; re-read next
}
else if (p == q)
// We have fallen off list. If tail is unchanged, it
// will also be off-list, in which case we need to
// jump to head, from which all live nodes are always
// reachable. Else the new tail is a better bet.
p = (t != (t = tail)) ? t : head;
else
// Check for tail updates after two hops.
p = (p != t && t != (t = tail)) ? t : q;
}
}

TA貢獻1993條經(jīng)驗 獲得超6個贊
添加回答
舉報