使用CopyOnWriteArrayList解决并发修改异常
package com.gwolf;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class TetCopyOnWriteArrayList {
public static void main(String[] args) {
HelloThread helloThread = new HelloThread();
for(int i = 0;i < 10;i++) {
new Thread(helloThread).start();
}
}
}
class HelloThread implements Runnable {
//private static List list = Collections.synchronizedList(new ArrayList<>());
private static CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();
static {
list.add("A");
list.add("B");
list.add("C");
}
@Override
public void run() {
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
list.add("a");
}
}
}