[英]Why use System.out.print when I can just System.out.println?
[英]Why concurrentmodificationexception when print a set with System.out.println()?
我正在實踐中閱讀Java Concurrency ,根據其中的一些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
?
假設2個線程A
和B
執行方法addTenThings()
。 他們可以做到,因為該方法不同步。
然后,如果在線程A
執行set
toString()
方法的過程中,從而對其進行迭代,則線程B
仍在執行循環,並調用add()
方法,這可能導致ConcurrentModificationException
,因為兩個線程都在運行僅在同一set
。 什么都不會停止線程來執行add(r.nextInt())
語句,而另一個線程正在執行方法中的print
語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.