线程不安全之集合不安全

 1 package 多线程练习.不安全线程;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 /*
 7    没有实际创建那么多线程
 8  */
 9 public class UnSafeList {
10     public static void main(String[] args) {
11         List<String> list = new ArrayList<>();
12 
13         for (int i = 0; i < 10000; i++) {
14             new Thread(() -> list.add(Thread.currentThread().getName())).start();
15         }
16 
17         // Sleep就是为了扩大事情的发展面
18         try {
19             Thread.sleep(3000);
20         } catch (InterruptedException e) {
21             e.printStackTrace();
22         }
23 
24         System.out.println("数量为:" + list.size());
25 
26     }
27 }

输出结果

原文地址:https://www.cnblogs.com/wooroc/p/15808281.html