首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >并发读写BlockingQueue

并发读写BlockingQueue
EN

Stack Overflow用户
提问于 2017-06-22 10:30:45
回答 1查看 1.6K关注 0票数 1

我在数据库前面使用LinkedBlockingQueue。一个线程写入队列,另一个线程从队列中读取。

我认为两次并发写入是不可能的。但是,一个线程是否有可能同时从队列读取另一个线程呢?如果没有,在Java中是否有一个队列提供这种功能?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-22 10:42:24

是的,有可能一个线程是读取,另一个是同时写入

LinkedBlockingQueue为此使用了两个锁。一种用于从队列中提取项目,另一种用于放置项目。

代码语言:javascript
复制
/** Lock held by put, offer, etc */
private final ReentrantLock putLock = new ReentrantLock();

/** Lock held by take, poll, etc */
private final ReentrantLock takeLock = new ReentrantLock();

讨论了在LinkedBlockingQueue上的实现方法,并在其源文件(第77行)中进行了讨论。

代码语言:javascript
复制
/*
 * A variant of the "two lock queue" algorithm.  The putLock gates
 * entry to put (and offer), and has an associated condition for
 * waiting puts.  Similarly for the takeLock.  The "count" field
 * that they both rely on is maintained as an atomic to avoid
 * needing to get both locks in most cases. Also, to minimize need
 * for puts to get takeLock and vice-versa, cascading notifies are
 * used. When a put notices that it has enabled at least one take,
 * it signals taker. That taker in turn signals others if more
 * items have been entered since the signal. And symmetrically for
 * takes signalling puts. Operations such as remove(Object) and
 * iterators acquire both locks.
 */
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44696845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档