标签:
Collections.synchronizedMap:实现了线程安全的特性
ConcurrentHashMap:保证了线程安全的同时也兼顾了并发访问的性能,将整个数据集合分成了若干个块
import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 可扩展集合类 */ public class AccessingMap { private static void userMap(final Map<String, Integer> scores) { scores.put("Joes", 90); scores.put("Mike", 85); try { for(final String key : scores.keySet()) { System.out.println(key + " " + scores.get(key)); scores.put("Tom", 99); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { System.out.println("Using HashMap"); userMap(new HashMap<String, Integer>());// System.out.println("Using synchronized HashMap"); userMap(Collections.synchronizedMap(new HashMap<String, Integer>()));//实现了线程安全的特性 System.out.println("Using ConcurrentHashMap"); userMap(new ConcurrentHashMap<String, Integer>());//保证了线程安全的同时也兼顾了并发访问的性能,将整个数据集合分成了若干个块 } }
标签:
原文地址:http://www.cnblogs.com/hellocyc/p/4265715.html