1. List,Map,Set 线程安全性
接口 | 具体实现 | 安全性 |
List | ArrayList | 不安全 |
LinkedList | 不安全 | |
Vector/Stack | 安全 | |
Map | HashMap | 不安全 |
HashTable | 安全 | |
LinkedHashMap | 不安全 | |
TreeMap | 不安全 | |
WeakHashMap | 不安全 | |
Set | HashSet | 不安全 |
LinkedHashSet | 不安全 | |
TreeSet | 不安全 |
2. 声明线程安全的集合方法
– 使用Collections. 方式构建
//make thread-safe list
List MyStrList = Collections.synchronizedList(new ArrayList());
MyStrList.add("123");
MyStrList.add("abc");
//make thread-safe hashset
Set set=Collections.synchronizedSet(new HashSet());
set.add(123);
set.add(456);
//make thread-safe hashmap
Map map=Collections.synchronizedMap(new HashMap());
map.put(1, "thb");
map.put(12, "bill tang");
– 使用ThreadLocal封装