ArrayList多线程添加元素异常,怎么解决

public static void main(String[] args) {
Random random = new Random();
int i = random.nextInt(20);
ArrayList arrayList = new ArrayList<>();
for (int i1 = 0; i1 < i; i1++) {
new Thread(()->{
arrayList.add(Thread.currentThread().getName());
}).start();
}
System.out.println(arrayList);
}


1个回答

 public static void main(String[] args) {
Random random = new Random();
int i = random.nextInt(20);
ArrayList arrayList = new ArrayList<>();
Object lockobj = new Object();
for (int i1 = 0; i1 < i; i1++) {
new Thread(()->{
synchronized(lockobj) {
arrayList.add(Thread.currentThread().getName());
}
}).start();
}
System.out.println(arrayList);
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐