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);
}
}
putIfAbsent 当 key 不存在时可以设置值
test.isComplated.putIfAbsent("create", true);
put 可以覆盖已存在的值
test.isComplated.put("story", true);