public class ConcurrentStack<E> { private AtomicReference<Node<E>> top = new AtomicReference<Node<E>>(); ConcurrentStack(){ } public void push(E item) { Node<E> newHead = new Node<E>(item); Node<E> oldHead = null; do { oldHead = top.get(); newHead.next = oldHead; } while (!top.compareAndSet(oldHead, newHead)); } public E pop() { Node<E> newHead = null; Node<E> oldHead = null; do { oldHead = top.get(); if (oldHead == null) { // return null; continue; } newHead = oldHead.next; } while (oldHead == null || !top.compareAndSet(oldHead, newHead)); return oldHead.item; } private static class Node<E> { public final E item; public Node<E> next; public Node(E item) { this.item = item; } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)