线程不安全的集合
ArrayList、LinkedList、HashSet、TreeSet、HashMap、TreeMap等都是线程不安全的,也就是说,当多个并发线程向这些集合中存、取元素时,就可能破坏这些集合的数据完整性。
如果程序中有多个线程可能访问以上这些集合,就可以使用Collection提供的类方法把这些集合包装成线程安全的集合。
static <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对象.
//举个例子
static List<Socket> socketList = Collections.synchronizedList(new ArrayList<>());
public Map<K, V> map = Collections.synchronizedMap(new HashMap<K, V>());
线程安全的集合
以Concurrent开头的集合类,如ConcurrentHashMap、ConcurrentSkipListMap、ConcurrentSkip ListSet、ConcurrentLinkedQueue和ConcurrentLinkedDeque。
以CopyOnWrite开头的集合类,如CopyOnWriteArrayList、CopyOnWriteArraySet。