如何创建同步数组列表

2022-01-22 00:00:00 multithreading synchronization java

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

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.

相关文章