对于从ConcurrentHashMap中取到的value,如果操作完之后重复对key赋新的value值,需要注意线程安全问题;使用while循环和replace方法,规避问题
public class OptionNotSafe implements Runnable {
private static ConcurrentHashMap<String, Integer> scores = new ConcurrentHashMap<>();
public static void main(String[] args) throws InterruptedException {
scores.put("小明", 0);
OptionNotSafe notSafe = new OptionNotSafe();
Thread thread1 = new Thread(notSafe);
Thread thread2 = new Thread(notSafe);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(scores);
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
while (true) {
Integer score = scores.get("小明");
int newScore = score + 1;
boolean b = scores.replace("小明", score, newScore);
if (b) {
break;
}
}
}
}
}