1
我在數據庫前使用LinkedBlockingQueue。一個線程寫入隊列,另一個線程讀取隊列。併發讀取和寫入BlockingQueue
兩個併發寫入應該是不可能的我想。但是有可能一個線程寫入,另一個線程同時從隊列中讀取?如果沒有,是否有一個隊列在Java中提供這個功能?
我在數據庫前使用LinkedBlockingQueue。一個線程寫入隊列,另一個線程讀取隊列。併發讀取和寫入BlockingQueue
兩個併發寫入應該是不可能的我想。但是有可能一個線程寫入,另一個線程同時從隊列中讀取?如果沒有,是否有一個隊列在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.
*/
是的。 'LinkedBlockingQueue'不僅僅是一個同步的'LinkedList'。 –
你可以閱讀javadoc,這裏都有討論。 –