如何创建同步数组列表 [英] how to create Synchronized arraylist

查看:13
本文介绍了如何创建同步数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了这样的同步数组列表

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 ?

推荐答案

synchronizedListIterator没有(也不能)同步,需要同步迭代时手动列表(请参阅 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.

这篇关于如何创建同步数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆