我有一个arrayList,我在两个线程之间共享,并且我试图同时遍历和修改列表。我不想使用迭代器的方法,我也使用了同步列表,但它仍然提供了concurrentmodificationexception
。
代码如下:
public class testing {
public static void main(String args[]){
ArrayList<String> al = new ArrayList<String>();
List<String> sal=Collections.synchronizedList(al);
String names[] = {"amol","Robin","vikas","shanu","mahesh"};
for(String x :names){
al.add(x);
}
Thread t1 = new Thread(new SyncArrayList(sal));
Thread t2 = new Thread(new SyncArrayList(sal));
t1.setName("T1");
t2.setName("T2");
t1.start();
t2.start();
}
}
class SyncArrayList implements Runnable
{
List<String> unsync ;
SyncArrayList(List<String> l){
this.unsync = l;
}
@Override
public void run() {
displayUnsyncList();
addNames();
}
void displayUnsyncList(){
synchronized(this){
ListIterator<String> itr = unsync.listIterator();
while(itr.hasNext()){
String x = itr.next();
System.out.println("Thread " +Thread.currentThread().getName() + " is displaying name : "+x);
}
}
}
void addNames(){
unsync.add("preet");
}
}
最佳答案
Collections.synchronizedList(...)
的javadoc说明了您需要执行的操作:
void displayUnsyncList() {
synchronized (unsync) {
ListIterator<String> itr = unsync.listIterator();
while (itr.hasNext()) {
String x = itr.next();
System.out.println("Thread " +
Thread.currentThread().getName() +
" is displaying name : " + x);
}
}
简而言之,您的代码正在错误的对象上进行同步。