Java線程的學習_線程與集合

線程不安全的集合

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。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章