从学习java开始就知道vector使用synchronized对方法进行加锁,所以线程安全但性能较低,但随着java的对于锁的优化,现在似乎已经不是这样了,下面开始验证一下
package com.kevindai.jdk8;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;
/**
* Create by daiwenkai
* on 2018/2/8 上午11:49
*/
public class TestListVector {
public static void main(String[] args) throws Exception {
List<Long> arrayList = new ArrayList<>();
List<Long> linkedList = new LinkedList<>();
Vector<Long> vector = new Vector<>();
CountDownLatch countDownLatch1 = new CountDownLatch(50000);
CountDownLatch countDownLatch2 = new CountDownLatch(50000);
CountDownLatch countDownLatch3 = new CountDownLatch(50000);
Long t1 = 0l;
Long t2 = 0l;
Long t3 = 0l;
Long s1 = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
Thread thread = new Thread(() -> {
arrayList.add(System.currentTimeMillis());
countDownLatch1.countDown();
});
thread.start();
}
for (int i = 0; i < arrayList.size(); i++) {
arrayList.get(i);
}
countDownLatch1.await();
Long e1 =System.currentTimeMillis();
t1 = e1 - s1;
Long s2 = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
Thread thread = new Thread(() -> {
linkedList.add(System.currentTimeMillis());
countDownLatch2.countDown();
});
thread.start();
}
countDownLatch2.await();
//这段代码有时候会报空指针异常,原因未知,很奇怪
for (int i = 0; i < linkedList.size(); i++) {
linkedList.get(i);
}
//这段代码有时候会报空指针异常,原因未知,很奇怪
Long e2 =System.currentTimeMillis();
t2 = e2 - s2;
Long s3 = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
Thread thread = new Thread(() -> {
vector.add(System.currentTimeMillis());
countDownLatch3.countDown();
});
thread.start();
}
countDownLatch3.await();
for (int i = 0; i < vector.size(); i++) {
vector.get(i);
}
Long e3 =System.currentTimeMillis();
t3 = e3 - s3;
System.out.println("arrayList:" + arrayList.size() + "," + t1);
System.out.println("linkedList:" + linkedList.size() + "," + t2);
System.out.println("vector:" + vector.size() + "," + t3);
}
}
上面这个demo是用多线程分别往ArrayList、LinkedList、Vector中插入50000个元素,然后读取出来,结果如下图
可以看到vector的速度反而最快
所以啊,要保持不断的学习,跟上技术的更新啊!