线程不安全的ArrayList

时间:2021-01-19 18:28:35

概述


java.util.ArrayList不是线程安全的,当有多个线程并发读写ArrayList的时候,ArrayList会抛出如下异常

java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
at java.util.ArrayList$Itr.next(ArrayList.java:791)

代码演示


import java.util.List;

public class ReadThread implements Runnable{
private List<String> list ;
public ReadThread(List<String> list) {
this.list = list;
}

@Override
public void run() {
for(String ele : list) {
System.out.println(ele);
}
}
}

import java.util.List;

public class WriteThread implements Runnable{
private List<String> list ;
public WriteThread(List<String> list) {
this.list = list;
}

@Override
public void run() {
this.list.add("11");
}
}

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ArrayListConCurrentWriteReadTest {

private void test() {
//1、准备数据
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");

//2、模拟多线程对list进行读和写
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
executorService.execute(new ReadThread(list));
executorService.execute(new WriteThread(list));
}
}


public static void main(String[] args) {
new ArrayListConCurrentWriteReadTest().test();
}
}

运行上面的代码就会抛出java.util.ConcurrentModificationException