我已经编辑了我的问题并使其非常简单。首先在同一个文件中有两个类 HashMapClass:创建 ConccurentHashMap 和 NewThread 的实例:更新 hashMap
public class HashMapClass {
public static volatile ConcurrentHashMap serverMap = new ConcurrentHashMap();
public static void main(String args[]) {
NewThread nt = new NewThread();
nt.start();
}
}
class NewThread extends Thread {
@Override
public void run() {
HashMapClass.serverMap.put("Ishan", new Integer(3));
System.out.println("Hash map is empty or not " + HashMapClass.serverMap.isEmpty());
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(NewThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
现在这里显示 hashMap 不为空,但如果我尝试从其他类 New Class 访问它,它显示为空
public class NewClass {
public static void main(String s[]) {
System.out.println("Hash map is empty or not " + HashMapClass.serverMap.isEmpty());
Set setMap = HashMapClass.serverMap.entrySet();
Iterator i = setMap.iterator();
for (int f = 0; i.hasNext(); ++f) {
Map.Entry me = (Map.Entry) i.next();
System.out.println("key is" + me.getKey() + "value is :" + me.getValue());
}
}
}
这个类永远不会用数据更新。我希望现在这很容易理解。