目录

一、背景

二、测试

三、详解

四、总结

一、背景

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

线程安全的list:

List vector = new Vector<>();

List listSyn = Collections.synchronizedList(new ArrayList<>());

List copyList = new CopyOnWriteArrayList<>();

二、测试

package com.yc.jdk.conllection;

import java.util.*;

import java.util.concurrent.CopyOnWriteArrayList;

/**

* @Author BigData-YC

* @Date 2021/10/23 7:33 下午

* @Version 1.0

*/

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 < num; i++) {

new Thread(() -> list.add(Math.round(0))).start();

}

}

}

执行的结果:

测试结果

并发数100100010000Vector85148836Collections649716CopyOnWriteArrayList1559512

三、详解

ArrayList线程不安全:主要是多线程在写入数据时,会有重复写入的问题 Vector线程安全:主要是在添加元素的时候,加上了synchronized public synchronized E set(int index, E element) {

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版本就有的集合是一个重量级的,不建议使用。