011Java併發包008集合中的執行緒安全問題
阿新 • • 發佈:2021-10-08
本文主要演示了集合在多執行緒環境下的併發修改問題。
1 List
1.1 程式碼
程式碼如下:
1 public static void main(String[] args) { 2 List<String> list = new ArrayList<>(); 3 for (int i = 0; i < 10; i++) { 4 new Thread(() -> { 5 list.add(UUID.randomUUID().toString().substring(0, 8)); 6 System.out.println(list); 7 }, String.valueOf(i)).start();8 } 9 }
1.2 執行
執行結果出現異常:
1 Exception in thread "1" Exception in thread "8" java.util.ConcurrentModificationException
說明出現了併發修改異常。
2 Set
2.1 程式碼
程式碼如下:
1 public static void main(String[] args) { 2 Set<String> set = new HashSet<>(); 3 for (int i = 0; i < 10; i++) { 4 new Thread(() -> {5 set.add(UUID.randomUUID().toString().substring(0, 8)); 6 System.out.println(set); 7 }, String.valueOf(i)).start(); 8 } 9 }
2.2 執行
執行結果出現異常:
1 Exception in thread "1" Exception in thread "8" java.util.ConcurrentModificationException
說明出現了併發修改異常。
3 Map
3.1 程式碼
程式碼如下:
1 public staticvoid main(String[] args) { 2 Map<String, String> map = new HashMap<>(); 3 for (int i = 0; i < 10; i++) { 4 String key = String.valueOf(i); 5 new Thread(() -> { 6 map.put(key, UUID.randomUUID().toString().substring(0, 8)); 7 System.out.println(map); 8 }, String.valueOf(i)).start(); 9 } 10 }
3.2 執行
執行結果出現異常:
1 Exception in thread "1" Exception in thread "8" java.util.ConcurrentModificationException
說明出現了併發修改異常。