对比在ConcurrentLinkedQueue中查询队列中元素数量size()和isEmpty()的性能差距

对比在ConcurrentLinkedQueue中查询队列中元素数量size()和isEmpty()的性能差距

package com.dwz.concurrent;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 *	并发集合
 *	对比在ConcurrentLinkedQueue中查询队列中元素数量size()和isEmpty()的性能差距
 */
public class ConcurrentLinkedQueueExample {
	
	public static void useSize() {
		final ConcurrentLinkedQueue<Long> queue = new ConcurrentLinkedQueue<>();
		
		for(int i = 0; i < 100000; i++) {
			queue.offer(System.nanoTime());
		}
		
		System.out.println("========= offer done ==========");
		long startTime = System.currentTimeMillis();
		while(queue.size() > 0) {
			queue.poll();
		}
		
		System.out.println("========= poll done ==========");
		System.out.println("useSize: " + (System.currentTimeMillis() - startTime));
	}
	
	public static void useIsEmpty() {
		final ConcurrentLinkedQueue<Long> queue = new ConcurrentLinkedQueue<>();
		
		for(int i = 0; i < 100000; i++) {
			queue.offer(System.nanoTime());
		}
		
		System.out.println("========= offer done ==========");
		long startTime = System.currentTimeMillis();
		while(!queue.isEmpty()) {
			queue.poll();
		}
		
		System.out.println("========= poll done ==========");
		System.out.println("useIsEmpty: " + (System.currentTimeMillis() - startTime));
	}
	
	public static void main(String[] args) {
		useSize();
		useIsEmpty();
	}
}

  代码运行结果

========= offer done ==========
========= poll done ==========
useSize: 12340
========= offer done ==========
========= poll done ==========
useIsEmpty: 3

  测试结果:

ConcurrentLinkedQueue的isEmpty()比size()效率高很多
posted @ 2020-10-12 10:29  龙宇在天  阅读(698)  评论(0编辑  收藏  举报
//右侧添加目录 //增加页面点击显示24字社会主义核心价值观