日期:2014-05-20 浏览次数:20871 次
public class TT { public static void main(String[] args) { //模拟3200次 for(int y=0;y<3200;y++){ Hashtable<Integer, String> hts = new Hashtable<Integer, String>(); for(int i=0;i<300;i++){ hts.put(i, "value="+i); } new Thread(new TestThread2(hts)).start(); new Thread(new TestThread(hts)).start(); } } }
public class TestThread implements Runnable { private Hashtable<Integer, String> hts; public TestThread(Hashtable<Integer, String> hts) { this.hts = hts; } @Override public void run() { //移除 hts.remove(1); } }
public class TestThread2 implements Runnable { private Hashtable<Integer, String> hts; public TestThread2(Hashtable<Integer, String> hts) { this.hts = hts; } @Override public void run() { // 遍历 //方法1 Iterator<Integer> it = hts.keySet().iterator(); while(it.hasNext()){ int k= it.next(); //此处抛 ConcurrentModificationException System.out.println(k); } //方法2 // Enumeration<Integer> e = hts.keys(); // while (e.hasMoreElements()) { // int key = e.nextElement(); //多次测试此处不会抛异常 // System.out.println(key+"--"+hts.get(key)); // } } }