A synchronized collection with Collections.synchronizedCollection : synchronized « Thread « Java Tutorial






import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

class MyThread implements Runnable {
  Thread t;

  Collection<String> col;

  MyThread(Collection<String> c) {
    col = c;
    t = new Thread(this, "MyThread");
    t.start();
  }

  public void run() {
    try {
      Thread.sleep(100);
      col.add("D");
      synchronized (col) {
        for (String str : col) {
          System.out.println("MyThread: " + str);
          Thread.sleep(50);
        }
      }
    } catch (Exception exc) {
      exc.printStackTrace();
    }
  }
}

public class Main {
  public static void main(String args[]) throws Exception {
    Set<String> tsStr = new TreeSet<String>();
    Collection<String> syncCol = Collections.synchronizedCollection(tsStr);

    syncCol.add("A");
    syncCol.add("B");
    syncCol.add("C");

    new MyThread(syncCol);

    synchronized (syncCol) {
      for (String str : syncCol) {
        System.out.println("Main thread: " + str);
        Thread.sleep(500);
      }
    }
  }
}








10.11.synchronized
10.11.1.Test Synchronized method
10.11.2.Test Unsynchronized method
10.11.3.This program is not synchronized.
10.11.4.This program uses a synchronized block.
10.11.5.Flag Communication
10.11.6.Waiting on an object
10.11.7.wait() and notify() must only be issued inside a synchronized block
10.11.8.guarantee that threads are woken in the same order in which they waited
10.11.9.creating a piped communications system between two threads.
10.11.10.Handle concurrent read/write: use synchronized to lock the data
10.11.11.A synchronized collection with Collections.synchronizedCollection
10.11.12.Determining If the Current Thread Is Holding a Synchronized Lock