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");
}
}
拋出的Exculate是ConcurrentModificationException,我在想代碼是不是修改列表(不是結構上)。Collections.sort方法在多線程環境中有時會拋出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)
我有方法,它返回的最大出名單,我不想USR Collections.max(),我想在多線程ENV列表與collections.sort方法的幫助下進行排序。
Collections.sort方法有時會在多線程環境中拋出ConcurrentModificationException。列表沒有被修改結構。
任何人都可以幫助我嗎?
您使用的是哪個版本的Java? – 2015-03-31 03:22:51
我問,因爲['Collections#sort']的版本(http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/Collections.java ?av = f),我正在查看不會調用'ArrayList#sort'。 – 2015-03-31 04:15:14