Java Collections synchronizedNavigableMap()
synchronizedNavigableMap() 用于获取由指定的NavigableMap支持的同步(线程安全)NavigableMap。
1 语法
public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m)
2 参数
m:它是NavigableMap,将被包装在同步的NavigableMap中。
3 返回值
4 synchronizedNavigableMap()示例1
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.synchronizedNavigableMap的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
NavigableMap<String, String> map = new TreeMap<String, String>();
map.put("3", "Java");
map.put("4", "Yiidian");
map.put("2", "Facebook");
map.put("1", "Google");
Map<String, String> synmap = Collections.synchronizedNavigableMap(map);
System.out.println("Synchronized navigable map is :" + synmap);
}
}
输出结果为:
Synchronized navigable map is :{1=Google, 2=Facebook, 3=Java, 4=Yiidian}
5 synchronizedNavigableMap()示例2
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.synchronizedNavigableMap的例子
*/
import java.util.*;
public class Demo {
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(map);
map.remove(4, 1004);
System.out.println("Synchronized navigable map after remove(4, 1004):" + synmap);
}
}
输出结果为:
Map before Synchronized navigable map: {1=1001, 2=1002, 3=1003, 4=1004, 5=1005}
Synchronized navigable map after remove(4, 1004):{1=1001, 2=1002, 3=1003, 5=1005}
6 synchronizedNavigableMap()示例3
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.synchronizedNavigableMap的例子
*/
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 Demo {
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(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
}
}
输出结果为:
10
热门文章
优秀文章