多线程操作HashMap
publicclassHashMapTestimplementsRunnable{Map<String,String>map=newHashtable<String,St...
public class HashMapTest implements Runnable{
Map<String,String> map=new Hashtable<String,String>();
@Override
public void run() {
this.putV();
}
public void putV(){
for (int j = 0; j < 3; j++) {
String key="aa"+j;
String value="AA"+j;
map.put(key, value);
}
Set<String> keySet = map.keySet();
for (String str : keySet) {
System.out.println("key:"+str+"; value:"+map.get(str));
}
}
public static void main(String[] args) {
Thread the1=new Thread(new HashMapTest());
Thread the2=new Thread(new HashMapTest());
the1.start();
the2.start();
}
}
执行结果:
key:aa2; value:AA2
key:aa2; value:AA2
key:aa1; value:AA1
key:aa0; value:AA0
key:aa1; value:AA1
key:aa0; value:AA0
问题:
为什么key重名但不会被后来的替换掉,这里public synchronized void putV()也是一样的结果 展开
Map<String,String> map=new Hashtable<String,String>();
@Override
public void run() {
this.putV();
}
public void putV(){
for (int j = 0; j < 3; j++) {
String key="aa"+j;
String value="AA"+j;
map.put(key, value);
}
Set<String> keySet = map.keySet();
for (String str : keySet) {
System.out.println("key:"+str+"; value:"+map.get(str));
}
}
public static void main(String[] args) {
Thread the1=new Thread(new HashMapTest());
Thread the2=new Thread(new HashMapTest());
the1.start();
the2.start();
}
}
执行结果:
key:aa2; value:AA2
key:aa2; value:AA2
key:aa1; value:AA1
key:aa0; value:AA0
key:aa1; value:AA1
key:aa0; value:AA0
问题:
为什么key重名但不会被后来的替换掉,这里public synchronized void putV()也是一样的结果 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询