Java Collections synchronizedMap()方法及实例
java.util.Collections 类的 synchronizedMap() 方法是用来返回一个由指定Map支持的同步(线程安全)Map。为了保证串行访问,对支持Map的所有访问都要通过返回的Map完成,这一点非常关键。
语法
public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)
参数: 该方法将Map作为参数,被 “包裹 “在一个同步Map中。
返回值: 该方法返回一个指定Map的同步视图。
下面是说明synchronizedMap()方法的例子。
例1 :
// Java program to demonstrate
// synchronizedMap() method
// for <String, String> Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of Map<String, String>
Map<String, String>
map = new HashMap<String, String>();
// populate the map
map.put("Value1", "20");
map.put("Value2", "30");
map.put("Value3", "40");
// printing the Collection
System.out.println("Map : " + map);
// create a synchronized map
Map<String, String>
synmap = Collections.synchronizedMap(map);
// printing the Collection
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 program to demonstrate
// synchronizedMap() method
// for <String, Boolean> Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of Map<String, Boolean>
Map<String, Boolean>
map = new HashMap<String, Boolean>();
// populate the map
map.put("Bramha", true);
map.put("Vishnu", true);
map.put("Mahesh", true);
// printing the Collection
System.out.println("Map : " + map);
// create a synchronized map
Map<String, Boolean>
synmap = Collections.synchronizedMap(map);
// printing the Collection
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}