Java Collection How to - Add to synchronized List by many threads








Question

We would like to know how to add to synchronized List by many threads.

Answer

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
//from ww w. ja  va 2s.  c  o  m
public class Main {
  public static void main(String[] args) throws InterruptedException {
     runTest();
  }
  private static void runTest() throws InterruptedException {
    Collection<String> syncList = Collections
        .synchronizedList(new ArrayList<String>(1));
    List<String> list = Arrays.asList("A", "B", "C", "D");
    List<Thread> threads = new ArrayList<Thread>();
    for (final String s : list) {
      Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
          syncList.add(s);
        }
      });
      threads.add(thread);
      thread.start();
    }
    for (Thread thread : threads) {
      thread.join();
    }
    System.out.println(syncList);
  }
}

The code above generates the following result.