我在看Java Concurrency in Practice,根据里面的一些java代码,System.out.println()
会导致ConcurrentModificationException
. 代码如下:
private final Set<Integer> set = new HashSet<Integer>();
public synchronized void add(Integer i) {set.add(i); }
public synchronized void remove(Integer i) {set.remove(i);}
public void addTenThings() {
Random r = new Random();
for (int i = 0; i < 10; i++) {
add(r.nextInt());
}
System.out.println("DEBUG: add ten elements to " + set );
}
由于该System.out.println()
方法只会调用该toString
方法:
public String toString() {
Iterator<E> i = iterator();
if (! i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
我还是不明白为什么ConcurrentModificationException
会被抛出??