ArrayBlockingQueue

ArrayBlockingQueue是由数组实现的有界阻塞队列,数据遵循FIFO先进先出的顺序,一旦创建容量固定无法修改。尝试put一个元素到满队列则阻塞等待,尝试
take一个元素到满队列亦阻塞等待。支持可选的公平策略控制等待的生产者和消费者获取数据的顺序,默认顺序是无法保证的。public ArrayBlockingQueue(int capacity, boolean fair)
通过构造函数将fair设置为true能保证线程访问的顺序按照FIFO,这种模式下会降低吞吐量但也能减少可变性、避免饥饿。

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {

/**
* Serialization ID. This class relies on default serialization
* even for the items array, which is default-serialized, even if
* it is empty. Otherwise it could not be declared final, which is
* necessary here.
*/
private static final long serialVersionUID = -817911632652898426L;

/** The queued items */
final Object[] items;

/** items index for next take, poll, peek or remove */
int takeIndex;

/** items index for next put, offer, or add */
int putIndex;

/** Number of elements in the queue */
int count;

/*
* Concurrency control uses the classic two-condition algorithm
* found in any textbook.
*/

/** Main lock guarding all access */
final ReentrantLock lock;//控制线程的数据访问顺序

/** Condition for waiting takes */
private final Condition notEmpty;//条件等待:消费者等待获取数据

/** Condition for waiting puts */
private final Condition notFull;//条件等待:生产者等待放入数据
... ...
/**
* Creates an {@code ArrayBlockingQueue} with the given (fixed)
* capacity and the specified access policy.
*
* @param capacity the capacity of this queue
* @param fair if {@code true} then queue accesses for threads blocked
* on insertion or removal, are processed in FIFO order;
* if {@code false} the access order is unspecified.
* @throws IllegalArgumentException if {@code capacity < 1}
*/
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}

坚持原创技术分享,您的支持将鼓励我继续创作!