同步不起作用,仍然java.util.ConcurrentModificationException

时间:2018-07-16 13:53:46

标签: java hashset synchronized

我有以下Java代码:

但是同步处理效果不好,帮助!

java.util.ConcurrentModificationException

  

java.util.ConcurrentModificationException在   java.util.HashMap $ HashIterator.nextNode(HashMap.java:1442)在   java.util.HashMap $ KeyIterator.next(HashMap.java:1466)在   java.util.AbstractCollection.toArray(AbstractCollection.java:196)在   位于Main.lambda $ main $ 0(Main.java:25)处的Main.m(Main.java:68)   java.lang.Thread.run(Thread.java:748)

public class Main {

    public static Set<Object> objectSet = new HashSet<>();

    public static void main(String[] args) throws Exception {

        new Thread(()->{m();}).start();
        new Thread(()->{add();}).start();
     }   
    public static void add() {
        while (true){
            objectSet.add(new Object());
        }

    }
    public static void m(){
        while(true){
            try {
                synchronized (objectSet) {
                    List a = Arrays.asList(objectSet.toArray(new Object[0]));
                    System.out.println(a.size());
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            try {
                Thread.sleep(1000);
            }catch (Exception e){

            }
        }
    }
}

无法同步(java.util.ConcurrentModificationException)

1 个答案:

答案 0 :(得分:0)

作者还应该在同一个对象上进行同步

add方法更改为

public static void add() {
    while (true) {
        synchronized (objectSet) {
            objectSet.add(new Object());
        }
    }

}