常见的操作接口有: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());
  }
不然会导致无法确定的行为。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-18
  • 2021-05-29
  • 2022-12-23
  • 2021-04-21
  • 2021-11-15
猜你喜欢
  • 2021-08-15
  • 2022-12-23
  • 2021-09-11
  • 2022-12-23
  • 2021-06-17
  • 2022-12-23
  • 2021-09-21
相关资源
相似解决方案