how to create Synchronized arraylist(如何创建同步数组列表)
问题描述
我已经创建了这样的同步数组列表
i have created synchronized arrayList like this
import java.text.SimpleDateFormat;
import java.util.*;
class HelloThread
{
int i=1;
List arrayList;
public void go()
{
arrayList=Collections.synchronizedList(new ArrayList());
Thread thread1=new Thread(new Runnable() {
public void run() {
while(i<=10)
{
arrayList.add(i);
i++;
}
}
});
thread1.start();
Thread thred2=new Thread(new Runnable() {
public void run() {
while(true)
{
Iterator it=arrayList.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
});
thred2.start();
}
}
public class test
{
public static void main(String[] args)
{
HelloThread hello=new HelloThread();
hello.go();
}
}
但是遇到这样的异常
线程Thread-1"java.util.ConcurrentModificationException 中的异常
Exception in thread "Thread-1" java.util.ConcurrentModificationException
我的方法有什么问题吗?
anything wrong in my approach ?
推荐答案
synchronizedList
的Iterator
没有(也不能)同步,需要同步迭代时手动列表(请参阅 javadoc):
Iterator
of synchronizedList
is not (and can't be) synchronized, you need to synchronize on the list manually while iterating (see javadoc):
synchronized(arrayList) {
Iterator it=arrayList.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
另一种方法是使用 CopyOnWriteArrayList
而不是 Collections.synchronizedList()
.它实现了写时复制语义,因此不需要同步.
Another approach is to use a CopyOnWriteArrayList
instead of Collections.synchronizedList()
. It implements a copy-on-write semantic and therefore doesn't require synchronization.
这篇关于如何创建同步数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何创建同步数组列表


基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01