Read/Write Lock

public class SomeContainer { private Set<element> elements; private ReadWriteLock globalLock; private Lock readLock; private Lock writeLock; SomeContainer() {  elements = new HashSet<element>();  globalLock = new ReentrantReadWriteLock();  readLock = globalLock.readLock();  writeLock = globalLock.writeLock(); }  public void addElement(Element elem) {  writeLock.lock();  try {   elements.add(elem);  }  finally {   writeLock.unlock();  }  }  public void processElements(ElementProcessor processor) {  readLock.lock();  try {   Iterator<element> iter = elements.iterator();    while(iter.hasNext()) {     Element element = iter.next();     processor.processElement(element);  }  finally {   readLock.unlock(); }  // ... }interface ElementProcessor { void processElement(Element element);}

So, in the example above, the first line in processElements will let everybody play at once so long as the write lock is not held. Then, when the write lock is requested, the requesting thread will be made to wait until all existing readers are done (no further readers will be let in), and then the writer thread may begin.

 

http://www.javalobby.com/java/forums/t45090.html

你可能感兴趣的:(thread,html)