在以下代码片段中,我尝试了所谓的线程安全Hashtable
和HashMap
。但在两种情况下,我得到ConcurrentModificationExceptionn
。如果是这样,那么什么是线程安全Hashtable和HashMap之间有什么区别,如果两者在下面的代码片段中抛出ConcurrentModificationException?
public class multiThreadedEnv {
static Map<Integer, String> map = new Hashtable<Integer, String>();
//static Map<Integer, String> map = new HashMap<Integer, String>();
static{
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
map.put(4, "Four");
map.put(5, "Five");
}
public static void main(String[] args) {
Thread t1 = new Thread(){
public void run() {
Iterator itr= map.entrySet().iterator();
while(itr.hasNext()){
Entry<String,String> entry=(Entry<String, String>) itr.next();
System.out.println(entry.getKey()+" , "+entry.getValue());
itr.remove();
Thread.sleep(2000);
}
}
};
Thread t2= new Thread(){
public void run() {
Iterator itr= map.entrySet().iterator();
while(itr.hasNext()) {
Entry<String,String> entry=(Entry<String, String>) itr.next();
System.out.println(entry.getKey()+" , "+entry.getValue());
itr.remove();
Thread.sleep(2000);
}
}
};
t1.start();
t2.start();
}
}
“Hashtable”本质上被弃用的全部原因是它让你思考你有没有线程安全。 –
可能重复的[如何调试ConcurrentModificationException?](http://stackoverflow.com/questions/840165/how-to-debug-concurrentmodificationexception) – Raedwald
@LouisWasserman当你说'Hashtable'和“deprecated”时要小心当我在听力范围内的时候判刑。 :-) –