Java Collections synchronizedSortedMap()
synchronizedSortedMap() 用于获取由指定的SortedMap支持的同步(线程安全)SortedMap。
1 语法
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)
2 参数
m:它是已排序的Map,它将包装在同步的SortedMap中。
3 返回值
返回在指定的同步SortedMap。
4 synchronizedSortedMap()示例1
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.synchronizedSortedMap的例子
*/
import java.util.*;
public class Demo {
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(map);
System.out.println("Synchronized sorted map is :" + sortmap);
}
}
输出结果为:
Synchronized sorted map is :{1=Whatsapp, 2=Twitter, 3=Facebook, 4=Instagram}
5 synchronizedSortedMap()示例2
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.synchronizedSortedMap的例子
*/
import java.util.*;
public class Demo {
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(map);
System.out.println("Synchronized sorted map:" + synmap);
}
}
输出结果为:
Synchronized sorted map:{1=1001, 2=1002, 3=1003, 4=1004, 5=1005}
6 synchronizedSortedMap()示例3
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.synchronizedSortedMap的例子
*/
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 Demo {
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(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
热门文章
优秀文章