Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1585845
  • 博文数量: 399
  • 博客积分: 8508
  • 博客等级: 中将
  • 技术积分: 5302
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-14 09:28
个人简介

能力强的人善于解决问题,有智慧的人善于绕过问题。 区别很微妙,小心谨慎做后者。

文章分类

全部博文(399)

文章存档

2018年(3)

2017年(1)

2016年(1)

2015年(69)

2013年(14)

2012年(17)

2011年(12)

2010年(189)

2009年(93)

分类: 架构设计与优化

2015-05-02 16:32:27

public class ConcurrentStack {
    
     AtomicReference> top = new AtomicReference>();

     public void push(E item) {
         Node newHead = new Node(item);
         Node oldHead;
         do {
             oldHead = top.get();
             newHead.next = oldHead;
         } while (!top.compareAndSet(oldHead, newHead));
     }

     public E pop() {
         Node oldHead;
         Node 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 {
    public final E item;
    public Node next;
    public Node(E item) {
        this.item = item;
    }
}
}

public class ConcurrentLinkedQueue {
private static class Node {
    final E item;
    final AtomicReference> next;
    public Node(E item, Node next) {
        this.item = item;
        this.next = new AtomicReference>(next);
    }
   private final Node dummy = new Node(null, null);
   private final AtomicReference> head = new AtomicReference>(dummy);
   private final AtomicReference> tail = new AtomicReference>(dummy);}
   public boolean put(E item) {
    Node newNode = new Node(item, null);
    while (true) {
             Node curTail = tail.get();
             Node tailNext = curTail.next.get();
             if (curTail == tail.get()) {
                 if (tailNext != null) {
                     // Queue in intermediate state, advance tail
                     tail.compareAndSet(curTail, tailNext);
                 } else {
                     // In quiescent state, try inserting new node
                     if (curTail.next.compareAndSet(null, newNode)) {
                         // Insertion succeeded, try advancing tail
                         tail.compareAndSet(curTail, newNode);
                         return true;
                    }
                 }
            }
    }
}



阅读(984) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~