java.util.ConcurrentModificationException

来源:互联网 发布:东南大学翻译硕士 知乎 编辑:程序博客网 时间:2024/06/07 20:14

map被两个线程访问,一个遍历,一个修改元素时会导致java.util.ConcurrentModificationException的异常,此事将HashMap改为ConcurrentHashMap,即可同步map内元素操作。

【HashMap和ConcurrentHashMap的区别见:http://blog.csdn.net/xuefeng0707/article/details/40834595】

public class Test {

    Map map = new HashMap();
    /** 
     * @Description 
     * @author 许凯勋
     * @date 2017年1月11日 下午3:31:53 
     * @param args  
     */
    public static void main(String[] args) {
       Test test = new Test();
       test.testMap();
       
    }  
    
    public void testMap(){
        Thread thread1 = new Thread("Thread1"){  
            @Override  
            public void run() {  
                int i = 0;
                while(i <100000000){
                    try {
                        sleep(500);
                    }
                    catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    i++;
                    map.put(i, i+1);
                }
            }  
        };  
        thread1.start();
        Thread thread2 = new Thread("Thread2"){  
            @Override  
            public void run() {  
                while(true){
                    Iterator it = map.keySet().iterator();  
                    while(it.hasNext()) {  
                    Object ele = it.next();  
//                        map.remove(ele);    //wrong  
                    }   
                }
            }  
        };  
        thread2.start();
    }
}
0 0
原创粉丝点击