多线程下操作集合
public class ListTest {
public static void main(String
[] args
) {
List
<String> list
= new ArrayList<>();
for (int i
=1;i
<=10;i
++){
new Thread(() -> {
list
.add(UUID
.randomUUID().toString().substring(0,5));
System
.out
.println(list
);
}).start();
}
}
}
会报错:并发修改异常 ConcurrentModificationException
解决方案
1. 使用vector
public class ListTest {
public static void main(String
[] args
) {
List
<String> list
= new Vector<>();
for (int i
=1;i
<=10;i
++){
new Thread(() -> {
list
.add(UUID
.randomUUID().toString().substring(0,5));
System
.out
.println(list
);
}).start();
}
}
}
问题:使用的synchronized效率低,版本较老
2. 使用 List list = Collections.synchronizedList(new ArrayList<>());
public class Demo1 {
public static void main(String
[] args
) {
List
<String> list
= Collections
.synchronizedList(new ArrayList<>());
for (int i
=1;i
<=10;i
++){
new Thread(() -> {
list
.add(UUID
.randomUUID().toString().substring(0,5));
System
.out
.println(list
);
}).start();
}
}
}
普通的解决方案
3.使用JUC中的CopyOnWriteArrayList<>();
public class Demo1 {
public static void main(String
[] args
) {
List
<String> list
= new CopyOnWriteArrayList<>();
for (int i
=1;i
<=10;i
++){
new Thread(() -> {
list
.add(UUID
.randomUUID().toString().substring(0,5));
System
.out
.println(list
);
}).start();
}
}
}
使用lock锁
set同理
map多线程下使用:concurentHashMap()
转载请注明原文地址:https://tech.qufami.com/read-5974.html