此实现来自:点击打开链接
具体如下:
package com.test;
import java.util.concurrent.atomic.AtomicReference;
public class ConcurrentStack<E>
{
private AtomicReference<Node<E>> head = new AtomicReference<Node<E>>();
public void push(E item)
{
Node<E> newHead = new Node<E>(item);
Node<E> oldHead;
do
{
oldHead = head.get();
newHead.next = oldHead;
}while(!head.compareAndSet(oldHead, newHead));
}
public E pop()
{
Node<E> newHead;
Node<E> oldHead;
for(;;)
{
oldHead = head.get();
newHead = oldHead.next;
if(head.compareAndSet(oldHead, newHead))
{
return oldHead.item;
}
}
}
static class Node<E>
{
final E item;
Node<E> next;
public Node(E item)
{
this.item = item;
}
}
}