为什么线程不安全?
E.G.:
这里使用多个线程同时处理一个 ArrayList ,期望输出 list.size
是 4000
List<String> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
list.add("list");
}
}).start();
}
Thread.sleep(10000);
System.out.println("List Size: " + list.size());
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == null) {
System.out.println("Error!");
}
}
System.out.println("Done!");
Output:
很显然结果总是不如人意的,不然我们也不用讨论呢。@_@
List Size: 1819
Error!
Error!
Error!
Error!
Error!
Error!
...
Done!
什么造成:
接下来我们看看 ArrayList.add
的具体实现,关键原因就是 add
里面地址索引增加操作