how to create Synchronized arraylist

前端 未结 7 1465
轻奢々
轻奢々 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条回答
  •  萌比男神i
    2020-12-15 08:35

    As Spike said, you can't modify a collection while iterating it. However, I think the solution is to lock the list while iterating.

    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)
      {
    synchronized(someLock) {
       arrayList.add(i);
    }
       i++;
      }
      }
     });
     thread1.start();
     Thread thred2=new Thread(new Runnable() {
      public void run() {
         while(true)
         {
    synchronized(someLock) {
       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();
      }
    }
    

    I'm not sure what you're trying to do, so I hope this doesn't break the functionality of your code.

提交回复
热议问题