Read/Write Lock

博客介绍了一个线程读写锁的示例,当写锁未被持有时,所有线程可同时操作;当请求写锁时,请求线程需等待所有现有读操作完成,且后续读操作将被阻止,之后写线程才能开始。
  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);</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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值