hooyantsing's Blog

21_CopyOnWriteArrayList

字数统计: 98阅读时长: 1 min
2020/08/22

21 CopyOnWriteArrayList

狂神说Java 多线程详解

学习前面的章节,知道 ArrayList 是线程不安全的。

CopyOnWriteArrayList 是线程安全的。属于JUC(java.util.concurrent)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package sync;

import java.util.concurrent.CopyOnWriteArrayList;

public class TestCopyOnWriteArrayList {
public static void main(String[] args) throws InterruptedException {
CopyOnWriteArrayList list = new CopyOnWriteArrayList();
for (int i = 0; i < 10000; i++) {
new Thread(
() -> list.add(Thread.currentThread().getName())
).start();
}

Thread.sleep(3000);
System.out.println(list.size());
}
}

运行结果:

.png

CATALOG
  1. 1. 21 CopyOnWriteArrayList