集合不安全
程序员文章站
2022-07-15 09:25:38
...
- Arraylist线程不安全,add方法没有锁
- 会出现ConcurrentModificationException()异常
- vector线程安全,但是并发性下降
Arraylist出现异常
public class test07 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 1;i<=30;i++){
new Thread(() -> {
list.add(UUID.randomUUID().toString().substring(0,8));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
- 解决方法:
- new Vector()<>;
- Collections.synchronizedList(new ArrayList<>());
- CopyOnWriteArrayList<>();读写分离
public class test07 {
public static void main(String[] args) {
List<String> list = Collections.synchronizedList(new ArrayList<>());
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 1;i<=30;i++){
new Thread(() -> {
list.add(UUID.randomUUID().toString().substring(0,8));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
上一篇: 算法:计算十进制数字在二进制表示1的个数