Java 一个HashMap,两个线程-在本例中如何确保线程安全?

Java 一个HashMap,两个线程-在本例中如何确保线程安全?,java,hashmap,thread-safety,Java,Hashmap,Thread Safety,我有一个关于线程安全和HashMaps的问题。更具体地说,我想知道是否有一个线程在写入HashMap时试图读取它。下面是一个粗略的例子: 我有一个叫做TestClass的类: public class TestClass implements Runnable { // New thread TestThread testThread = new TestThread(); @Override public void run() { // S

我有一个关于线程安全和HashMaps的问题。更具体地说,我想知道是否有一个线程在写入HashMap时试图读取它。下面是一个粗略的例子:

我有一个叫做TestClass的类:

public class TestClass implements Runnable {

    // New thread
    TestThread testThread = new TestThread();

    @Override
    public void run() {

        // Starts the thread.
        testThread.start();

        // A copy of testHashMap is retrieved from the other thread.
        // This class often reads from the HashMap.
        // It's the only class that reads from the HashMap.
        while (true) {
            HashMap<String, Long> testHashMap = testThread.get();

        }
    }
}
我还有另一个类叫做TestThread:

public class TestThread extends Thread {

    private HashMap<String, Long> testHashMap = new HashMap<>();

    @Override
    public void run() {

        // This thread performs a series of calculations once a second.
        // After the calculations are done, they're saved to testHashMap with put().
        // This is the only thread that writes to testHashMap.

    }

    // This method returns a copy of testHashMap. This method is used by the Test class.
    public HashMap<String, Long> get() {
        return testHashMap;
    }

}
get方法是否可能在TestThread写入testHashMap时尝试复制testHashMap?如果是这样的话,在本例中如何确保线程安全?我必须创建同步映射而不是哈希映射吗

提前谢谢

get方法是否可能在TestThread写入testHashMap时尝试复制testHashMap

不需要。get方法只返回映射。这里禁止复制

但是,您必须以某种方式控制对映射的访问,因为HashMap不是线程安全的。您可以通过同步hashmap=Collections.synchronizedMapnew hashmap来实现这一点;或者使用ConcurrentHashMap。

改用: