记录下ConcurrentHashMap学习,记录日期2017.5.18
1.ConcurrentHashMap——实现类,接口是ConcurrentMap,线程安全,属于java.util.concurrent多线程包下
2.理解putIfAbsent 方法含义
package com.qbao.sms.common.annotation;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Description:
*
* @author suoww
* @date 2017/5/18
*/
public class Test {
public static void main(String[] args){
//测试ConcurrentHashMap putIfAbsent//
ConcurrentMap<String,Integer> concurrentMap = new ConcurrentHashMap<String, Integer>(10);
concurrentMap.put("张三", 1);
Integer value1 = concurrentMap.putIfAbsent("张三" , 10);
Integer value2 = concurrentMap.putIfAbsent("李欣" , 20);
System.out.println(value1);
System.out.println(value2);
Set<String> keySet = concurrentMap.keySet();
for (String key: keySet) {
System.out.println(key + "||" + concurrentMap.get(key));
}
System.out.println("--------------");
//HashMap
Map<String,Integer> hashMap = new HashMap<String, Integer>(10);
hashMap.put("张三", 1);
Integer value3 = hashMap.put("张三" , 10);
Integer value4 = hashMap.put("李欣" , 20);
System.out.println(value3);
System.out.println(value4);
Set<String> keySet2 = hashMap.keySet();
for (String key: keySet2) {
System.out.println(key + "||" + hashMap.get(key));
}
}
}
总结:
1.和hashMap比较发现,ConcurrentHashMap通过使用putIfAbsent可以保证特定key对应的value值不会被其他线程所覆盖。putIfAbsent含义就是不存在某key value才会放进去,存在了则不会放进去。
2.无论ConcurrentHashMap还是HashMap返回值都是<K,V>中的V值