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.
这篇关于如何创建同步数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何创建同步数组列表
				
        
 
            
        - 未找到/usr/local/lib 中的库 2022-01-01
 - 转换 ldap 日期 2022-01-01
 - Eclipse 的最佳 XML 编辑器 2022-01-01
 - 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
 - 如何指定 CORS 的响应标头? 2022-01-01
 - GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
 - 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
 - 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
 - 获取数字的最后一位 2022-01-01
 - java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
 
						
						
						
						
						
				
				
				
				