这可能是一个重复的问题,但我在一本关于并发的书中找到了这段代码。据说这是线程安全的:
ConcurrentHashMap<String, Integer> counts = new ...;
private void countThing(String thing) {
while (true) {
Integer currentCount = counts.get(thing);
if (currentCount == null) {
if (counts.putIfAbsent(thing, 1) == null)
break;
} else if (counts.replace(thing, currentCount, currentCount + 1)) {
break;
}
}
}
从我(并发初学者)的角度来看,线程t1和线程t2都可以读取到currentCount = 1
。然后两个线程都可以将映射的值更改为2。请问有人可以解释一下这段代码是否正确吗?