总结篇----list类(主要划分为线程安全和不安全)

前言

这次主要把list类划分为线程安全和不安全

线程不安全的List类

1、LinkList

  • 增删快
  • 里面含有大量操作首尾数组的方法

2、Arraylist

  • 查询快
  • 大小可变的数组实现

线程安全的List类

(并不是说这些类都基于list)

1、Vector

从JDK1.0开始,Vector便存在JDK中,Vector是一个线程安全的列表,采用数组实现。其线程安全的实现方式是对所有操作都加上了synchronized关键字,这种方式严重影响效率,因此,不再推荐使用Vector了

2、Collections.synchronizedList

  • 读写操作都比较均匀
  • 执行add()等方法的时候是加了synchronized关键字的,但是遍历listIterator(),iterator()却没有加.所以在使用的时候需要加上synchronized.

使用方法:

 List<String> list = Collections.synchronizedList(new ArrayList<String>());
    list.add("a");
    synchronized (list) {
        Iterator it = list.iterator(); 
        while (it.hasNext()) {
            System.out.println(i.next());
        }
    }

3、CopyOnWriteArrayList

基本原理:

  • CopyOnWriteArrayList容器允许并发读,读操作是无锁的,性能较高。至于写操作,比如向容器中添加一个元素,则首先将当前容器复制一份,然后在新副本上执行写操作,结束之后再将原容器的引用指向新容器

优缺点:

  • 读操作性能很高,因为无需任何同步措施,比较适用于读多写少的并发场景
  • 每次执行写操作都要将原容器拷贝一份,内存占用大
  • 读写分离,提高了读的效率,但是有时不能保证其数据的一致性

猜你喜欢

转载自blog.csdn.net/weixin_43157543/article/details/107410126