JavaCollections SynchronizedSortedMap()
Java集合类的
synchronizedSortedMap()方法用于获取同步(线程安全的)排序映射,由指定的排序映射支持。
语法
以下是
synchronizedSortedMap()方法的声明:
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)
参数
参数 |
说明 |
必需/可选 |
m |
它是排序后的地图,将被包装在一个同步的排序后的地图中。 |
必需 |
返回
synchronizedSortedMap()方法返回指定排序的Map的同步视图。
异常
NA
示例1
import java.util.*;
public class CollectionsSynchronizedSortedMapExample1 {
public static void main(String[] args) {
SortedMap<String, String> map = new TreeMap<String, String>();
map.put("1", "Whatsapp");
map.put("4", "Instagram");
map.put("3", "Facebook");
map.put("2", "Twitter");
SortedMap<String, String> sortmap = Collections.synchronizedSortedMap</span>(map);
System.out.println("Synchronized sorted map is :" + sortmap);
}
}
输出:
Synchronized sorted map is :{1=Whatsapp, 2=Twitter, 3=Facebook, 4=Instagram}
示例2
import java.util.*;
public class CollectionsSynchronizedSortedMapExample2 {
public static void main(String[] args) {
SortedMap<Integer, Integer> map = new TreeMap<>();
map.put(1, 1001);
map.put(2, 1002);
map.put(5, 1005);
map.put(4, 1004);
map.put(3, 1003);
//System.out.println("Map before synchronized map: " + map);
SortedMap<Integer, Integer> synmap = Collections.synchronizedSortedMap</span>(map);
System.out.println("Synchronized sorted map:" + synmap);
}
}
输出:
Synchronized sorted map:{1=1001, 2=1002, 3=1003, 4=1004, 5=1005}
示例3
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class CollectionsSynchronizedSortedMapExample3 {
private static AtomicInteger counter = new AtomicInteger();
public static void main(String... args) throws InterruptedException {
SortedMap<Integer, Integer> m = new TreeMap<>();
SortedMap<Integer, Integer> map = Collections.synchronizedSortedMap</span>(m);
final ExecutorService e = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
e.execute(() -> map.put(counter.incrementAndGet(),
(int) (Math.random() * 100)));
}
e.shutdown();
e.awaitTermination(1000, TimeUnit.SECONDS);
System.out.println(map.size());//should be 10
}
}
输出: