Make List a Thread-Safe Class : Collections « Utility Classes « SCJP

Home
SCJP
1.Java Source And Data Type
2.Operators
3.Modifiers
4.Type Casting
5.Statements
6.Object Oriented
7.Thread
8.Utility Classes
9.File
SCJP » Utility Classes » Collections 
8.12.2.Make List a Thread-Safe Class
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class MainClass {
  private List names = Collections.synchronizedList(new LinkedList());

  public void add(String name) {
    names.add(name);
  }

  public String removeFirst() {
    if (names.size() 0)
      return (Stringnames.remove(0);
    else
      return null;
  }

  public static void main(String[] args) {
    final MainClass nl = new MainClass();
    nl.add("Ozymandias");
    class NameDropper extends Thread {
      public void run() {
        String name = nl.removeFirst();
        System.out.println(name);
      }
    }
    Thread t1 = new NameDropper();
    Thread t2 = new NameDropper();
    t1.start();
    t2.start();
  }
}
A
null
8.12.Collections
8.12.1.Java Collections
8.12.2.Make List a Thread-Safe Class
8.12.3.Sorting Collections and Arrays
8.12.4.Return a reference to a new Map that accesses the existing data but with synchronized methods
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.