下面例子用来做concurrentLinkedQueue和arrayList 加数据和减数据的性能比较
package day4;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentLinkedQueueDemo {
public static void main(String[] args) {
ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();
List list = new ArrayList();
ExecutorService executor = Executors.newFixedThreadPool(16);
ExecutorService executor2 = Executors.newFixedThreadPool(16);
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
executor.execute(new Thread(""+i){
public void run() {
queue.offer("value" + Thread.currentThread().getName());
}
});
}
for (int i = 0; i < 100000; i++) {
executor.execute(new Thread(""+i){
public void run() {
while(!queue.isEmpty()) {
queue.poll();
}
}
});
}
executor.shutdown();
System.out.println("ConcurrentLinkedQueue: "+(System.currentTimeMillis()-start));
long start2 = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
executor2.execute(new Thread(""+i){
public void run() {
synchronized (list) {
list.add("value" + Thread.currentThread().getName());
}
}
});
}
for (int i = 0; i < 100000; i++) {
executor2.execute(new Thread(""+i){
public void run() {
for(Iterator ite = list.iterator();ite.hasNext();) {
ite.next();
}
}
});
}
executor2.shutdown();
System.out.println("ArrayList: "+(System.currentTimeMillis()-start2));
}
}
console输出:
ConcurrentLinkedQueue: 348
ArrayList: 1331
注意:不要使用queue.size()来判断队列是否为空,因为此方法会遍历整个ConcurrentLinkedQueue