java集合之List线程安全性比较总结(性能比较)

您所在的位置:网站首页 多线程的同步调度方法有哪些 java集合之List线程安全性比较总结(性能比较)

java集合之List线程安全性比较总结(性能比较)

#java集合之List线程安全性比较总结(性能比较)| 来源: 网络整理| 查看: 265

文章目录 前言一、背景二、测试三、详解四、总结总结

前言

介绍三种安装es-head插件的方式 1、Google浏览器插件 安装Google浏览器插件,直接访问Elasticsearch 2、npm安装 下载源码,编译安装,在nodejs环境下运行插件

一、背景

在多线程中使用集合list时,会有线程不安全的问题。所以调研了所有的list线程安全的集合,同时使用简单的测试,测试出相对应的性能。 线程安全的list :

List vector = new Vector(); List listSyn = Collections.synchronizedList(new ArrayList()); List copyList = new CopyOnWriteArrayList(); 二、测试 package com.example.jkytest.juc; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; public class ListTest { // static List list = new ArrayList(); static List vector = new Vector(); static List listSyn = Collections.synchronizedList(new ArrayList()); static List copyList = new CopyOnWriteArrayList(); public static void main(String[] args) throws InterruptedException { // 设置并发数 int num = 100; List all = Arrays.asList(vector, listSyn, copyList); for (List list : all) { long start = System.currentTimeMillis(); test(num, list); System.out.println("------耗时:" + (System.currentTimeMillis() - start)); // 等待上述所有线程执行完 Thread.sleep(2 * 1000); } } /** * @param num 循环次数 * @param list 集合 */ public static void test(int num, List list) { for (int i = 0; i if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } Collections.synchronizedList:主要是一个大的集合框架里面也是synchronized public boolean add(E e) { synchronized (mutex) {return c.add(e);} } CopyOnWriteArrayList:主要是使用ReentrantLock,每次添加元素都会复制旧的数据到新的数组里面,同时使用锁 public boolean add(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len + 1); newElements[len] = e; setArray(newElements); return true; } finally { lock.unlock(); } } 四、总结

ArrayList 单线程中使用

多线程中,并发在2000以内的使用Collections.synchronizedList;并发在2000以上的使用CopyOnWriteArrayList;Vector是JDK1.1版本就有的集合是一个重量级的,不建议使用。

总结

如果此篇文章有帮助到您, 希望打大佬们能关注、点赞、收藏、评论支持一波,非常感谢大家! 如果有不对的地方请指正!!!

参考1



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3