Read/Write Lock

1714 단어 threadhtml
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);}</element></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

좋은 웹페이지 즐겨찾기