本文介绍了如何在HashMap中演示竞争条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java讲授并发编程,并想向学生展示使用非线程安全数据结构可能引起的问题。我创建了以下程序:

I am teaching concurrent programming in Java and would like to demonstrate to the students the problems that can arise by using non-thread-safe data structures. I created the following program:

    Map<String,String> favoriteFoods = new HashMap<>();
    Thread t1 = new Thread(() -> {
        favoriteFoods.put("Alice","avocado");
        favoriteFoods.put("Bob","banana");
    });
    Thread t2 = new Thread(() -> {
        favoriteFoods.put("Alice","aloysia");
        favoriteFoods.put("Carl","candy");
    });
    t1.start();
    t2.start();

    t1.join();
    t2.join();
    System.out.println(favoriteFoods);

其中从两个不同的线程访问非线程安全的HashMap。但是,该程序每次运行时都可以正常运行。

where a non-thread-safe HashMap is accessed from two different threads. However, the program works fine every time I run it.

如何更改代码以演示问题?

How can I change the code in order to demonstrate the problem?

推荐答案

尝试通过哈希冲突将元素添加到HashMap:

Try to add elements to HashMap with hash collisions:

import java.util.*;
public class HashMapRaceCondition2 {
    public static void main(String[] args) throws Exception {
        class MyClass {
            int value;

            MyClass(int value) {
                this.value = value;
            }

            @Override
            public boolean equals(Object o) {
                if (this == o) return true;
                if (o == null || getClass() != o.getClass()) return false;

                MyClass myClass = (MyClass) o;

                if (value != myClass.value) return false;

                return true;
            }

            @Override
            public int hashCode() {
                return 42;
            }

            @Override
            public String toString() {
                return "MyClass{" +
                        "value=" + value +
                        '}';
            }
        }  // MyClass

        Map<MyClass,Integer> map = new HashMap<>();

        Thread t1 = new Thread(() -> {
            for (int i =0; i < 1000; ++i) {
                map .put(new MyClass(i), i);
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 2000; i < 3000; ++i) {
                map.put(new MyClass(i), i);
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(map.size());
    }
}

此代码每5-6次在我的计算机上失败一次处决。

This code fails on my machine once per 5-6 executions.

这篇关于如何在HashMap中演示竞争条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 15:00