Java中的Collections synchronizedSortedMap()方法及其示例
java.util.Collections 类的 synchronizedSortedMap() 方法用于返回由指定的排序映射支持的同步(线程安全)排序映射。为了确保串行访问,必须通过返回的排序映射(或其视图)完成对后备排序映射的所有访问。
语法:
public static <K, V> SortedMapK, V>
synchronizedSortedMap(SortedMapK, V> m)
参数: 此方法将排序映射作为要包装为同步排序映射的参数。
返回值: 此方法返回指定排序映射的同步视图。
下面是示例,以说明 synchronizedSortedMap() 方法。
示例1:
// Java程序演示
// synchronizedSortedMap()方法
// 对于<String, String>值
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// 创建SortedMap<String, String>对象
SortedMap<String, String>
map = new TreeMap<String, String>();
// 填充映射
map.put("1", "A");
map.put("2", "B");
map.put("3", "C");
// 打印集合
System.out.println("排序后的Map: " + map);
// 创建排序后的映射
SortedMap<String, String>
sortedmap = Collections
.synchronizedSortedMap(map);
// 打印映射
System.out.println("同步排序后的Map: " + sortedmap);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
排序后的Map: {1=A, 2=B, 3=C}
同步排序后的Map: {1=A, 2=B, 3=C}
示例2:
// Java程序演示
// synchronizedSortedMap()方法
// 对于<Integer, Boolean>值
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// 创建SortedMap<Integer, Boolean>对象
SortedMap<Integer, Boolean>
map = new TreeMap<Integer, Boolean>();
// 填充映射
map.put(100, true);
map.put(200, true);
map.put(300, true);
// 打印集合
System.out.println("排序后的Map: " + map);
// 创建排序后的映射
SortedMap<Integer, Boolean>
sortedmap = Collections
.synchronizedSortedMap(map);
// 打印映射
System.out.println("同步排序后的Map: " + sortedmap);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
排序后的Map: {100=true, 200=true, 300=true}
同步排序后的Map: {100=true, 200=true, 300=true}