2017-06-22 79 views
1

我在数据库前使用LinkedBlockingQueue。一个线程写入队列,另一个线程读取队列。并发读取和写入BlockingQueue

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

+0

是的。 'LinkedBlockingQueue'不仅仅是一个同步的'LinkedList'。 –

+0

你可以阅读javadoc,这里都有讨论。 –

回答

1

是的,有可能一个线程是读取和一个是写入在同一时间。

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