- 使用BlockingQueue實(shí)現(xiàn)寫入日志隊(duì)列。
- 多用于生產(chǎn)者-消費(fèi)者模式
<pre>
以下是基于典型的生產(chǎn)者-使用者場景的一個(gè)用例氯窍。注意摔癣,BlockingQueue 可以安全地與多個(gè)生產(chǎn)者和多個(gè)使用者一起使用扑浸。
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();//某一個(gè)實(shí)現(xiàn)類
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>
內(nèi)存一致性效果:當(dāng)存在其他并發(fā) collection 時(shí),將對(duì)象放入BlockingQueue
之前的線程中的操作 happen-before后通過另一線程從 BlockingQueue 中訪問或移除該元素的操作兄渺。
實(shí)現(xiàn)類的對(duì)比--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.
參考文檔