声明: 此文章留作自己学习和补充使用
代码
public static void main(String[] args) {
ExecutorService threadPool = null;
try {
// 源集合
int size = 10000000;
List<Integer> srcList = new ArrayList<>();
for (int i = 0; i < size; i++) {
srcList.add(0);
}
long time1 = System.currentTimeMillis();
// 测试多线程设置list集合
// 1.存在线程安全问题 ArrayList
//List<Integer> resList = new ArrayList<Integer>(size);
// 2.线程安全集合 Vector
//List<Integer> resList = new Vector<Integer>(size);
// 3.线程安全集合 Collections.synchronizedList
List<Integer> resList = Collections.synchronizedList(new ArrayList<Integer>(size));
threadPool = Executors.newFixedThreadPool(200);
// 同步主线程
CountDownLatch main = new CountDownLatch(size);
for (Integer integer : srcList) {
threadPool.execute(() -> {
resList.add(integer + 1);
main.countDown();
});
}
// 唤醒主线程
main.await();
System.out.println(resList.size());
long time2 = System.currentTimeMillis();
System.out.println("耗时: "+(time2 - time1));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (threadPool != null) {
threadPool.shutdown();
}
}
}
执行结果
- 使用ArrayList
9991938
耗时: 5433
- 使用Vector
10000000
耗时: 8867
- 使用Collections.synchronizedList
10000000
耗时: 7895
说明
预期新集合size为10000000,但使用ArrayList存在线程安全问题,导致size < 10000000
多线程编程时需要操作的的公共List 可以使用Vector或使用 Collections中的synchronized相关方法,其内部的所有方法都是被synchronized修饰的,确保了list 操作的原子性和list对多线程的可见性
synchronizedList和Vector区别
见此文章https://blog.csdn.net/u014754272/article/details/105116400/