線程安全的集合操作類
阿新 • • 發佈:2017-12-03
iter 常見 zed linked 同步塊 無法 接口 ron 同步
常見的操作接口有:Map,List,Set,Vector 其最常用的實現類有:HashMap,ArrayList,LinkedList,HashSet
但是只有Vector是線程安全的,Collections實現了一個些方法可以保證常用的集合類達到線程安全:
Map: Map<Object,Object> map = Collections.synchronizedMap(new HashMap<>());
Set: Set<Object> set1 = Collections.synchronizedSet(new HashSet<>());
List: List<String> list = Collections.synchronizedList(new LinkedList<>());
List<String> list = Collections.synchronizedList(new ArrayList<>());
註意 使用時必須在同步塊中使用如:
Set s = Collections.synchronizedSet(new HashSet()); ... synchronized(s) { Iterator i = s.iterator(); // Must be in the synchronized block while (i.hasNext()) foo(i.next()); }
不然會導致無法確定的行為。
線程安全的集合操作類