我正在尝试实现以下功能: str 数组中的每个键都应与一个从 0 开始并将存储在 map 中的 Integer 相关联。执行后,映射应该包含 str 中的所有键,并且计数应该与最终值 9 一致。但是结果从 8 到 12 不等。我做错了什么?
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
public static final AtomicInteger count = new AtomicInteger(0);
public static final String[] str = {
"a", "b", "c", "d", "e", "f", "g", "h"
};
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
ExecutorService exe = Executors.newFixedThreadPool(4);
for (int j = 0; j < 100; j++) {
exe.execute(() -> {
for (int k = 0; k < 1000; k++) {
int index = k % 8;
String key = str[index];
Integer value = map.get(key);
if (value == null) {
Integer next = count.incrementAndGet();
map.putIfAbsent(key, next);
}
}
});
}
exe.shutdown();
exe.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("count = " + count.get());
}
}
}