基础知识总结:线程安全的集合与线程不安全的集合

来源:互联网 发布:跟易企秀类似的软件 编辑:程序博客网 时间:2024/06/07 12:22

集合大概有4种类型:List   Set   Queue  Map

其中Vector、HashTable、Properties是线程安全的。其中ArrayList、LinkedList、HashSet、TreeSet、HashMap、TreeMap等都是线程不安全的。(线程不安全是指:当多个线程访问同一个集合或Map时,如果有超过一个线程修改了ArrayList集合,则程序必须手动保证该集合的同步性。)

当多个并发同时对非线程安全的集合进行增删改的时候会破坏这些集合的数据完整性

Collections提供的类方法把这些集合包装成线程安全的集合。Collections提供了如下几个静态方法。
  • <T> Collection<T> synchronizedCollection(Collection<T> c): 返回指定collection 对应的线程安全的collection。
  • static <T> List<T> synchronizedList(List<T> list): 返回指定List对象对应的线程安全的List 对象。
  • static <K, V> Map<K, V> synchronizedMap(Map<K, V> m): 返回指定Map对象对应的线程安全的Map对象。
  • static <T> Set<T> synchronizedSet(Set<T> s): 返回指定Set对象对应的线程安全的Set对象。
  • static <K, V> SortedMap<K, V> synchronizedSortedMap(SortedMap<K, V> m): 返回指定SortedMap对象对应的线程安全的SortedMap对象。
  • static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s): 返回指定SortedSet对象对应的线程安全的SortedSet对象。

另外java.util.concurrent 包下提供了大量支持高效并发访问的集合接口和实现类:
  • 以Concurrent 开头的集合类,如ConcurrentHashMap、ConcurrentSkipListMap、ConcurrentSkipListSet、ConcurrentLinkedQueue 和 ConcurrentLinkedDeque。
  • 以CopyOnWrite 开头的集合类,如CopyOnWriteArrayList、CopyOnWriteArraySet。




原创粉丝点击