线程安全的集合操作类

常见的操作接口有:Map,List,Set,Vector 其最常用的实现类有:HashMap,ArrayList,LinkedList,HashSet

但是只有Vector是线程安全的,Collections实现了一个些方法可以保证常用的集合类达到线程安全:

Map: Map<Object,Object> map =  Collections.synchronizedMap(new HashMap<>());

java.util.concurrent包还提共了ConcurrentHashMap类:

Map<Object, Object> map = new ConcurrentHashMap<>();

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());
  }
不然会导致无法确定的行为。