ConcurrentLinkedQueue

    public static void main(String[] args) {
        ConcurrentLinkedQueue<Integer> concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
        // 三大操作 均是并发安全的
        boolean add1 = concurrentLinkedQueue.add(1);
        System.out.println(add1);
        boolean add2 = concurrentLinkedQueue.add(2);
        System.out.println(add2);
        Integer poll = concurrentLinkedQueue.poll();
        System.out.println(poll);
        boolean contains = concurrentLinkedQueue.contains(2);
        System.out.println(contains);
    }

因为没有实现BlockingQueue接口,所以是非阻塞队列。

怎么用CAS操作来实现插入正确性

先修改next的指定值再修改tali指针

随着线程增多,CAS一直判断十分消耗CPU,此时CAS性能会大幅度降低,因为CPU此时一直循环并没有做别有意义的事情。

ConcurrentLinkedQueue之add方法 

public boolean offer(E e) {
        final Node<E> newNode = new Node<E>(Objects.requireNonNull(e));

        for (Node<E> t = tail, p = t;;) {
            Node<E> q = p.next;
            if (q == null) {
                // p is last node
                if (NEXT.compareAndSet(p, null, newNode)) {
                    // Successful CAS is the linearization point
                    // for e to become an element of this queue,
                    // and for newNode to become "live".
                    if (p != t) // hop two nodes at a time; failure is OK
                        TAIL.weakCompareAndSet(this, t, newNode);
                    return true;
                }
                // Lost CAS race to another thread; re-read next
            }
            else if (p == q)
                // We have fallen off list.  If tail is unchanged, it
                // will also be off-list, in which case we need to
                // jump to head, from which all live nodes are always
                // reachable.  Else the new tail is a better bet.
                p = (t != (t = tail)) ? t : head;
            else
                // Check for tail updates after two hops.
                p = (p != t && t != (t = tail)) ? t : q;
        }
    }

通过自旋的方式,进行插入操作,不是阻塞队列。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值