Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

10.5. 线程安全的 HashMap(ConcurrentHashMap)

		
package cn.netkiller.test;

import java.util.concurrent.ConcurrentHashMap;

public class Test {
    private final ConcurrentHashMap<String, Boolean> isComplated = new ConcurrentHashMap<String, Boolean>();

    public static void main(String[] args) {
        Test test = new Test();
        test.isComplated.putIfAbsent("create", true);
        test.isComplated.putIfAbsent("story", false);
        test.isComplated.putIfAbsent("picture", true);

        boolean isDone = test.isComplated.values().stream().allMatch(status -> status);
        System.out.println(test.isComplated);
        System.out.println(isDone);

        test.isComplated.put("story", true);
        isDone = test.isComplated.values().stream().allMatch(status -> status);
        System.out.println(test.isComplated);
        System.out.println(isDone);
    }
}
		
		

10.5.1. 设置键与值

putIfAbsent 当 key 不存在时可以设置值

			
test.isComplated.putIfAbsent("create", true);	
			
			

put 可以覆盖已存在的值

		
test.isComplated.put("story", true);