Java Collections syncMap()
Java集合类的
synchronizedMap()方法用于获取同步的(线程安全的)映射
语法
以下是syncedMap()方法的声明:
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)
参数
参数 |
说明 |
必需/可选 |
m |
它将被包装在同步地图中。 |
必需 |
返回
synchronizedMap()方法返回指定Map的同步视图。
异常
不适用
示例1
import java.util.*;
public class CollectionsSynchronizedMapExample1 {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "Rahul");
map.put("4", "Karan");
map.put("3", "Mohan");
Map<String, String> synmap = Collections.synchronizedMap</span>(map);
System.out.println("Synchronized map is :" + synmap);
}
}
输出:
Synchronized map is :{1=Rahul, 3=Mohan, 4=Karan}
示例2
import java.util.*;
public class CollectionsSynchronizedMapExample2 {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
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 map: " + map);
Map<Integer, Integer> synmap = Collections.synchronizedMap</span>(map);
map.remove(4, 1004);
System.out.println("Synchronized 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.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class CollectionsSynchronizedMapExample3 {
private static AtomicInteger counter = new AtomicInteger();
public static void main(String[] args) throws InterruptedException{
Map<Integer, Integer> m = new HashMap<>();
Map<Integer, Integer> map = Collections.synchronizedMap</span>(m);
final ExecutorService e = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10000; 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 10000
}
}
输出: