这个方法在key不存在的时候加入一个值,如果key存在就不放入,等价:
if (!map.containsKey(key)) return map.put(key, value); else return map.get(key);
测试代码:
public class Test { public static void main(String[] args) { ConcurrentHashMap<String,String> map=new ConcurrentHashMap<String,String>(); String temp=map.putIfAbsent("a", "gaoxing"); System.out.println(map.get("a")); temp=map.putIfAbsent("a","nihao"); System.out.println(map.get("a")); temp=map.putIfAbsent("a","gaoxing"); System.out.println(map.get("a")); } }
结果为
gaoxing
gaoxing
gaoxing
ConcurrentHashMap的putIfAbsent用来做缓冲相当不错,多线程安全的
时间: 2024-11-13 06:36:32