how to create Synchronized arraylist

前端 未结 7 1450
轻奢々
轻奢々 2020-12-15 07:50

i have created synchronized arrayList like this

import java.text.SimpleDateFormat;
import java.util.*;


class HelloThread  
{

 int i=1;
 List arrayList;
           


        
7条回答
  •  温柔的废话
    2020-12-15 08:44

    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()); 
       } 
    }
    

    Another approach is to use a CopyOnWriteArrayList instead of Collections.synchronizedList(). It implements a copy-on-write semantic and therefore doesn't require synchronization.

提交回复
热议问题