2005-10-31

Read/Write Lock

关键字: reader-write-lock
public class SomeContainer { private Set elements; private ReadWriteLock globalLock; private Lock readLock; private Lock writeLock; SomeContainer() {  elements = new HashSet();  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 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

评论
发表评论

您还没有登录,请登录后发表评论

dengyin2000
搜索本博客
我的相册
4d063000-8eef-365d-8346-f210ccfd5265-thumb
VB-seamless
共 13 张
存档
最新评论