package CollectionsTS;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
public class ArrayListTS {
public static void main(String[] args) {
HashSet<Integer> hset = new HashSet<Integer>();
for (int i = 0; i <= 1000; i++) {
hset.add(i);
}
MyRunnable mr = new MyRunnable();
mr.addElements(hset);
Thread t1 = new Thread(mr,"t1");
Thread t2 = new Thread(mr,"t2");
Thread t3 = new Thread(mr,"t3");
t1.start(); t2.start(); t3.start();
}
}
class MyRunnable implements Runnable {
List<Integer> ilist = new ArrayList<Integer>();
public void addElements(HashSet<Integer> hset) {
ilist.addAll(hset);
}
@Override
public void run() {
Collections.sort(ilist);
if (ilist.size() > 0)
System.out.println( Thread.currentThread().getName() +" = "+ilist.get(ilist.size() - 1));
else
System.out.println("List is empty");
}
}
抛出的异常是ConcurrentModificationException,我在想代码没有修改列表(结构上),为什么会出现这个异常。
Exception in thread "t1" t3 = 1000
Exception in thread "t2" java.util.ConcurrentModificationException
at java.util.ArrayList.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at CollectionsTS.MyRunnable.run(ArrayListTS.java:37)
at java.lang.Thread.run(Unknown Source)
java.util.ConcurrentModificationException
at java.util.ArrayList.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at CollectionsTS.MyRunnable.run(ArrayListTS.java:37)
at java.lang.Thread.run(Unknown Source)
我有一个方法,它返回列表中的最大值,我不想使用Collections.max(),我想使用collections.sort方法在多线程环境下对列表进行排序。
Collections.sort方法有时会在多线程环境中引发ConcurrentModificationException。列表没有结构性修改。
有人可以帮我吗?
Collections#sort
版本没有调用ArrayList#sort
。 - Sotirios Delimanolis