接口 BlockingQueue<E>
阻塞队列,当队列为null的时候可以加入元素,当队列满的时候就等待。
所有已知实现类:
ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue
用该接口可以很容易实现生产者消费者问题。
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();
}
}
demo:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockQueueTest {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Object> queue = new ArrayBlockingQueue<>(3);
for (int i = 1; i < 40; i++) {
queue.put(i);
System.out.println(i);
}
System.out.println(queue.size());
Thread.sleep(100);
queue.remove();
}
}
该阻塞队列size为3,当加入第四个元素的时候,队列已满,程序等待如果有元素移除,会继续添加,直到40个元素添加满。
本文介绍了阻塞队列的概念及其实现类,并通过具体代码示例展示了如何使用阻塞队列来解决生产者消费者问题。
435

被折叠的 条评论
为什么被折叠?



