当前位置:  首页>> 技术小册>> Java语言基础10-Java中的集合

  • Collections 类提供了多个 synchronizedXxx() 方法,该方法可以将指定集合包装成线程安全的集合,从而可以解决多线程并发访问集合时的线程安全问题。
  • 将 Collection 集合转换为线程安全的集合:
  1. public static <T> Collection<T> synchronizedCollection(Collection<T> c) {}
  • 将 Set 集合转换为线程安全的集合:
  1. public static <T> Set<T> synchronizedSet(Set<T> s) {}
  • 将 List 集合转换为线程安全的集合:
  1. public static <T> List<T> synchronizedList(List<T> list) {}
  • 将 Map 集合转换为线程安全的集合:
  1. public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {}
  • 示例:
  1. package com.github.collections.demo2;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5. /**
  6. * @author maxiaoke.com
  7. * @version 1.0
  8. */
  9. public class Test {
  10. public static void main(String[] args) {
  11. List<String> list = Collections.synchronizedList(new ArrayList<>());
  12. list.add("aa");
  13. list.add("bb");
  14. list.add("cc");
  15. list.add("dd");
  16. list.add("ee");
  17. System.out.println("list = " + list);
  18. }
  19. }