在Java中使用synchronizedMap()方法创建集合的示例
java.util.Collections 类的 synchronizedMap() 方法用于返回由指定映射支持的同步(线程安全)映射。为了确保串行访问,非常重要的是对返回的映射执行对支持映射的所有访问。
语法:
public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)
参数: 该方法将一个地图作为参数,“包装”在同步地图中。
返回值: 该方法返回指定映射的同步视图。
下面是示例,说明synchronizedMap()方法。
示例1:
// Java程序演示
// synchronizedMap()方法
// for <String, String> Type
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// 创建Map<String, String>对象
Map<String, String>
map = new HashMap<String, String>();
// 填充映射
map.put("Value1", "20");
map.put("Value2", "30");
map.put("Value3", "40");
// 打印集合
System.out.println("Map : " + map);
// 创建一个同步地图
Map<String, String>
synmap = Collections.synchronizedMap(map);
// 打印集合
System.out.println("Synchronized map is : "
+ synmap);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Map : {Value3=40, Value1=20, Value2=30}
Synchronized map is : {Value3=40, Value1=20, Value2=30}
示例2:
// Java程序演示
// synchronizedMap()方法
// for <String, Boolean> Type
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// 创建Map<String, Boolean>对象
Map<String, Boolean>
map = new HashMap<String, Boolean>();
// 填充映射
map.put("Bramha", true);
map.put("Vishnu", true);
map.put("Mahesh", true);
// 打印集合
System.out.println("Map : " + map);
// 创建一个同步地图
Map<String, Boolean>
synmap = Collections.synchronizedMap(map);
// 打印集合
System.out.println("Synchronized map is : "
+ synmap);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Map : {Bramha=true, Vishnu=true, Mahesh=true}
Synchronized map is : {Bramha=true, Vishnu=true, Mahesh=true}