对于从ConcurrentHashMap中取到的value,如果操作完之后重复对key赋新的value值,需要注意线程安全问题;使用while循环和replace方法,规避问题

    1. public class OptionNotSafe implements Runnable {
    2. private static ConcurrentHashMap<String, Integer> scores = new ConcurrentHashMap<>();
    3. public static void main(String[] args) throws InterruptedException {
    4. scores.put("小明", 0);
    5. OptionNotSafe notSafe = new OptionNotSafe();
    6. Thread thread1 = new Thread(notSafe);
    7. Thread thread2 = new Thread(notSafe);
    8. thread1.start();
    9. thread2.start();
    10. thread1.join();
    11. thread2.join();
    12. System.out.println(scores);
    13. }
    14. @Override
    15. public void run() {
    16. for (int i = 0; i < 1000; i++) {
    17. while (true) {
    18. Integer score = scores.get("小明");
    19. int newScore = score + 1;
    20. boolean b = scores.replace("小明", score, newScore);
    21. if (b) {
    22. break;
    23. }
    24. }
    25. }
    26. }
    27. }

    https://www.bilibili.com/video/BV1gT4y1V7aZ?p=32