阻塞队列在jdk中的实现

实现类:

ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedTransferQueue, PriorityBlockingQueue, SynchronousQueue

阻塞式队列;

throw exception special value blocks time out
insert add(e) offer(e) put(e) offer(e, time, unit)
remove remove() poll() take() poll(time, unit)
examine element() peek

注:

  • 不能向队列中插入null值 NullPointerException
  • poll()在队列为空时,会返回null,而remove()会抛出NoSuchElementException.
  • remove(x)方法主要应用场景:当队列中的某个消息需要被取消
  • 主要用于producer-consumer场景
  • addAll, containsAll, retainAll and removeAll不是原子性的,除非个别实现类有特殊实现

方法说明

  • offer(e, time, unit)
    • 该方法会等待指定时间,若指定时间依然拿不到锁,则放弃执行。

线程安全(thread-safe)

在add,remove,put,take,poll,offer等操作中,都使用了锁机制,保证线程安全

应用场景

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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();
}
}
 上一页

 评论