Java TreeMap获取同步Map
TreeMap可以使用Collections.synchronizedMap()方法进行同步。Collections类的synchronizedMap()方法将需要同步化的Map作为参数,并返回一个线程安全的同步Map。java.util.Collections类的synchronizedMap()方法用于返回一个由指定Map支持的同步(线程安全)Map。为了保证串行访问,对支持地图的所有访问都是通过返回的地图完成的,这一点至关重要。
语法:
public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)
参数: 作为一个参数被 “包裹 “在一个同步地图中。
返回值: 的指定地图。
实施。
示例
// Java program to demonstrate
// synchronization of TreeMap
// Importing all classes from
// java.util package
import java.util.*;
// Class
public class GFG {
// Main driver method
public static void main(String[] args) throws Exception
{
// Try block to check if any exception occurs
try {
// Step1: Creating a TreeMap object
// Declaring object of string type
TreeMap<String, String> treeMap
= new TreeMap<String, String>();
// Step2: Adding elements into the above Map
// Custom inputs
treeMap.put("1", "Welcome");
treeMap.put("2", "To");
treeMap.put("3", "Geeks");
treeMap.put("4", "For");
treeMap.put("5", "Geeks");
// Printing all elements of the above Map object
System.out.println("Map : " + treeMap);
// Synchronizing the map using
// synchronizedMap() method of Collection class
Map<String, String> sMap
= Collections.synchronizedMap(treeMap);
// Printing the Collection
System.out.println("Synchronized map is : "
+ sMap);
}
// Catch block to handle the exceptions
catch (IllegalArgumentException e) {
// Displaying and printing the exception
System.out.println("Exception thrown : " + e);
}
}
}
输出
Map : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}
Synchronized map is : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}