CopyOnWriteArrayList
CopyOnWriteArrayList
ArrayList是多线程不安全的,建议使用CopyOnWriteArrayList
package com.example.juc;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* ArrayList多线程不安全,解决方法
* 1.Vector 效率不高,Vector.add底层是用synchronized实现的
* 2.Collections.synchronizedList 顾名思义,底层也是用synchronized实现的
* 3.CopyOnWriteArrayList 写入时复制,底层是用Lock实现的
*/
public class TestList {
public static void main(String[] args) {
// List<String> list = new ArrayList<>();
// List<String> list = new Vector<>();
// List<String> list = Collections.synchronizedList(new ArrayList<>());
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10; i++) {
new Thread(() -> {
list.add(UUID.randomUUID().toString().substring(0, 5));
System.out.println(list);
}, "" + i).start();
}
}
}