前提:基于x86体系结构,Linux环境
核心思想:基于链表进行实现
首先声明链表
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
进队(enqueue)
进队操作分三步:
- 创建新节点
- 将当前尾节点的 next指针指向新节点
- 修改尾指针指向新创建的节点
参考ConcurrentLinkedQueue 的poll方法
public E poll() {
restartFromHead: for (;;) {
for (Node<E> h = head, p = h, q;; p = q) {
final E item;
if ((item = p.item) != null && p.casItem(item, null)) {
// Successful CAS is the linearization point
// for item to be removed from this queue.
if (p != h) // hop two nodes at a time
updateHead(h, ((q = p.next) != null) ? q : p);
return item;
}
else if ((q = p.next) == null) {
updateHead(h, p);
return null;
}
else if (p == q)
continue restartFromHead;
}
}
}
`}
出队(dequeue)
出队操作相对入队要简单不少,只要把头指针向后移并拿出数据就可以了
好吧,我承认自己搞不懂这部分内容了,但是没办法还是要知道个大概的,就是为了面试而已,随便看看
参考论文:
- John D. Valois 1994年10月在拉斯维加斯的并行和分布系统系统国际大会上的一篇论文——《Implementing Lock-Free Queues》
- 美国纽约罗切斯特大学 Maged M. Michael 和 Michael L. Scott 在1996年3月发表的一篇论文 《Simple, Fast, and Practical Non-Blocking and Blocking ConcurrentQueue Algorithms》