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));
}
}