- 使用BlockingQueue實現寫入日志隊列。
- 多用于生產者-消費者模式
<pre>
以下是基于典型的生產者-使用者場景的一個用例。注意,BlockingQueue 可以安全地與多個生產者和多個使用者一起使用。
class Producer implements Runnable {
private final BlockingQueue queue;
Producer(BlockingQueue q) { queue = q; }
public void run() {
try {
while(true) { queue.put(produce()); }
} catch (InterruptedException ex) { ... handle ...}
}
Object produce() { ... }
}
class Consumer implements Runnable {
private final BlockingQueue queue;
Consumer(BlockingQueue q) { queue = q; }
public void run() {
try {
while(true) { consume(queue.take()); }
} catch (InterruptedException ex) { ... handle ...}
}
void consume(Object x) { ... }
}
class Setup {
void main() {
BlockingQueue q = new SomeQueueImplementation();//某一個實現類
Producer p = new Producer(q);
Consumer c1 = new Consumer(q);
Consumer c2 = new Consumer(q);
new Thread(p).start();
new Thread(c1).start();
new Thread(c2).start();
}
}
</pre>
內存一致性效果:當存在其他并發 collection 時,將對象放入BlockingQueue
之前的線程中的操作 happen-before后通過另一線程從 BlockingQueue 中訪問或移除該元素的操作。
實現類的對比--ArrayBlockingQueue vs ConcurrentLinkedQueue vs LinkedBlockingQueue vs LinkedList
As you can see from the provided performance results LinkedBlockingQueue achieved the best combined (adding and removing elements) performance results and should be your number one candidate for implementing producer – consumer schenarios.
參考文檔