java多线程——concurrentLinkQueue


concurrentLinkedQueue是一种非阻塞队列,通过CAS保证其操作过程中的原子性,
而又因为CAS本身为非阻塞式算法,因此该队列也为非阻塞式的。
在该队列内部,每一个节点都一个Node类。
同时,为了保持仅内存可见性,所以Node内部的域使用volatile修饰。
最后,和一般的链表队列一样,该队列也有头指针和尾指针,同样也都是Node类型的。


在操作时,如add(elem)操作:
首先用哨兵记录头指针,再将头指针遍历到队列尾部,此时其指向null。
然后,进行CAS操作:将头指针与null进行比较,如果是null,说明没有其他线程操作过,执行插入。
并且在concurrentLinkedQueue中,如果一个线程CAS失败,会无限自旋。。。


 


package concurrentLinkQueue;/*
name: demo01
user: ly
Date: 2020/5/30
Time: 16:48
*/

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;

//   :比较concurrentLinkedQueue与linkedBlockingQueue差别
public class demo01 {
    private static ConcurrentLinkedQueue<Integer> concurrentLinkedQueue = new ConcurrentLinkedQueue<Integer>();
    private static LinkedBlockingQueue<Integer> linkedBlockingQueue = new LinkedBlockingQueue<Integer>();

    public static void test1(){
        for(int i = 0;i < 100000;i++){
            Thread thread = new Thread(new Runnable() {
                public void run() {
                    int j = (int)(Math.random()*10);
                    concurrentLinkedQueue.add(j);
                }
            });
            thread.start();
        }

    }

    public static void test2(){
        for(int i = 0;i < 100000;i++){
            Thread thread = new Thread(new Runnable() {
                public void run() {
                    int j = (int)(Math.random()*10);
                    linkedBlockingQueue.add(j);
                }
            });
            thread.start();
        }
    }

    public static void main(String []args) throws InterruptedException{
        Thread thread = new Thread(new Runnable() {
            public void run() {
//                test1();
                test2();
            }
        });
        long start = System.currentTimeMillis();
        thread.start();
        thread.join();
        long end = System.currentTimeMillis();
//        System.out.println("the concurrentLinkedQueue consume time is :"+(end-start));
        System.out.println("the LinkedBlockingQueue consume time is :"+(end-start));
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值