当前位置: 首页>后端>正文

JUC:CopyOnWriteArrayList

JUC:CopyOnWriteArrayList,第1张

public class Thread07 {

public static void main(String[] args) {

// 并发修改异常ConcurrentModificationException

// List list = new ArrayList();

// 写入时复制、多个线程调用的时候、在写入的时候避免覆盖、造成数据丢失、读写分离

List list = new CopyOnWriteArrayList();

for (int i = 0; i < 10; i++) {

new Thread(()->{

list.add(UUID.randomUUID().toString().substring(0,3));

System.out.println(list);

},String.valueOf(i)).start();

}

// 底层源码

// ???????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();

// ???????????}

// ???????}

}

}


https://www.xamrdz.com/backend/3p21932390.html

相关文章: