Java.util.Collections 类

java.util.Collections.synchronizedMap() 方法返回由指定映射支持的同步(线程安全)映射.

语法

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)

这里,K和V分别是map维护的key和value的类型。

参数

m 指定要"包装"在同步map中的map。

返回值

返回指定map的同步视图。

异常

无。

示例:

在下面的示例中,java.util.Collections.synchronizedMap() 方法返回给定map的同步视图。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建Map对象
    Map<Integer, String> MyMap = new HashMap<Integer, String>();

    //填充MyMap
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");

    //打印map
    System.out.println("MyMap contains: " + MyMap); 

    //创建map的同步视图
    Map NewMap = Collections.synchronizedMap(MyMap);

    //打印同步map
    System.out.println("NewMap contains: " + NewMap); 
  }
}

上述代码的输出将是:

MyMap contains: {101=John, 102=Marry, 103=Kim}
NewMap contains: {101=John, 102=Marry, 103=Kim}