Java Collections syncNavigableMap()
Java集合类的
synchronizedNavigableMap()方法用于获取同步(线程安全)的可导航地图
语法
下面是
synchronizedNavigableMap()方法的声明:
public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m)
参数
参数 |
说明 |
必需/可选 |
m |
这是可导航地图,将被包装在同步的可导航地图中。 |
必需 |
返回
synchronizedNavigableMap()方法返回指定导航地图的同步视图。
异常
NA
兼容版本
Java 1.8及更高版本
示例1
import java.util.*;
public class CollectionsSynchronizedNavigableMapExample1 {
public static void main(String[] args) {
NavigableMap<String, String> map = new TreeMap<String, String>();
map.put("3", "Java");
map.put("4", "lidihuo");
map.put("2", "Facebook");
map.put("1", "Google");
Map<String, String> synmap = Collections.synchronizedNavigableMap</span>(map);
System.out.println("Synchronized navigable map is :" + synmap);
}
}
输出:
Synchronized navigable map is :{1=Google, 2=Facebook, 3=Java, 4=lidihuo}
示例2
import java.util.*;
public class CollectionsSynchronizedNavigableMapExample2 {
public static void main(String[] args) {
NavigableMap<Integer, Integer> map = new TreeMap<>();
map.put(1, 1001);
map.put(2, 1002);
map.put(3, 1003);
map.put(4, 1004);
map.put(5, 1005);
System.out.println("Map before synchronized navigable map: " + map);
Map<Integer, Integer> synmap = Collections.synchronizedNavigableMap</span>(map);
map.remove(4, 1004);
System.out.println("Synchronized navigable map after remove(4, 1004):" + synmap);
}
}
输出:
Map before synchronized map: {1=1001, 2=1002, 3=1003, 4=1004, 5=1005}
Synchronized map after remove(4, 1004):{1=1001, 2=1002, 3=1003, 5=1005}
示例3
import java.util.Collections;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class CollectionsSynchronizedNavigableMapExample3 {
private static AtomicInteger counter = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
NavigableMap<Integer, Integer> m = new TreeMap<>();
NavigableMap<Integer, Integer> map = Collections.synchronizedNavigableMap</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
}
}
输出: