本例中的非阻塞算法中能确保线程的安全性。
本例是摘自《JAVA并发编程实战》这本书的高级题部分
本例是摘自《JAVA并发编程实战》这本书的高级题部分
import java.util.concurrent.atomic.AtomicReference;
/**
* Created by nspace on 15-4-18.
*/
//@ThreadSafe
public class CocurrentStack<E> {
AtomicReference<Node<E>> top = new AtomicReference<Node<E>>();
public void push(E item) {
Node<E> newHead = new Node<E>(item);
Node<E> oldHead;
do {
oldHead = top.get();
newHead.next = oldHead;
} while (!top.compareAndSet(oldHead, newHead));
}
public E pop() {
Node<E> oldHead;
Node<E> newHead;
do {
oldHead = top.get();
if(oldHead == null) {
return null;
}
newHead = oldHead.next;
} while (!top.compareAndSet(oldHead, newHead));
return oldHead.item;
}
private static class Node<E> {
public final E item;
public Node<E> next;
private Node(E item) {
this.item = item;
}
}
}