SomeContainer Set<element> elements; ReadWriteLock globalLock; Lock readLock; Lock writeLock; SomeContainer() elements = HashSet<element>(); globalLock = ReentrantReadWriteLock(); readLock = globalLock.readLock(); writeLock = globalLock.writeLock(); addElement(Element elem) writeLock.lock(); elements.add(elem); writeLock.unlock(); processElements(ElementProcessor processor) readLock.lock(); Iterator<element> iter = elements.iterator(); (iter.hasNext()) Element element = iter.next(); processor.processElement(element); readLock.unlock(); ElementProcessor 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.
博客介绍了一个示例,在写锁未被持有时,所有线程可同时操作。当请求写锁时,请求线程需等待所有现有读操作完成,且不再允许新的读线程进入,之后写线程才能开始操作,还给出相关链接。
4371

被折叠的 条评论
为什么被折叠?



