gpt4 book ai didi

java - 如何遍历和修改这个 Arraylist?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:39:21 25 4
gpt4 key购买 nike

我有一个在两个线程之间共享的 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");
}

}

最佳答案

在多线程环境中,您应该考虑使用不会产生 ConcurrentModificationExceptionCopyOnWriteArrayList

关于java - 如何遍历和修改这个 Arraylist?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36061442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com