gpt4 book ai didi

java - BlockingQueue 的并发读写

转载 作者:行者123 更新时间:2023-11-30 02:29:13 31 4
gpt4 key购买 nike

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

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

最佳答案

是的,有可能一个线程同时和一个

LinkedBlockingQueue 为此使用两个锁。一个用于从队列中取出元素,另一个用于放置元素。

/** 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 的实现方式也在其source file (line 77)中进行了讨论。 .

/*
* 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.
*/

关于java - BlockingQueue 的并发读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44696845/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com