Java 集合与队列的插入、删除在并发下的性能比较(二)

2014-11-23 21:30:58 · 作者: · 浏览: 19
int i = 0; i < 104; i++)
108 service.pickOne();
109 }
110 }
111 }
112
113 /***
114 * 多线程方式,测试一个插入、删除工具
115 *
116 * @param service
117 * @param time
118 * @param unit
119 * @throws InterruptedException
120 */
121 private static void test(Service service, int time, TimeUnit unit)
122 throws InterruptedException {
123 ExecutorService execs = Executors.newCachedThreadPool();
124 for (int i = 0; i < 20; i++) {
125 execs.execute(new Tester(service));
126 }
127 execs.shutdown();
128 unit.sleep(time);
129 stop.compareAndSet(false, true);
130 service.tell();
131 }
132
133 public static void main(String[] args) throws InterruptedException {
134 Service setService = new SetService();
135 test(setService, 5, TimeUnit.SECONDS);
136 stop.compareAndSet(true, false);// 重置终止条件
137 Service queueService = new QueueService();
138 test(queueService, 5, TimeUnit.SECONDS);
139 }
140 }
复制代码
  输出的结果如下:
SetQueueTest$SetService@5e9de959 : 7149859
SetQueueTest$QueueService@11b343e0 : 24303408
  测试结果让我感到吃惊,TreeSet的插入删除效率确实比LinkedList低,20个线程跑了10秒,使用队列,插入删除24303408次,使用集合,插入删除7149859次。它们之间差距并不大,队列只比集合快2~3倍。属于同一个数量级。于是我这个小型的爬虫应该放心的选择用Set作为unVistedUrls的实现。