ConcurrentHashMap学习笔记一

记录下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值







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值