LinkedBlockingQueue 类的作用:
首先有三个关键字:
1.Linked
2.Blocking
3.Queue
1.首先是一个队列。
2.是一个阻塞队列。
3.由链表实现。
作用:
当你放一个元素的时候,当LinkedBlockingQueue 已经满了,如果调用put方法,那么你存放的线程就会阻塞,直到其他线程从队列中取出元素,这时候你就可以放进队列。但是如果调用offer方法,那么offer方法直接会返回false.不会阻塞线程。
LinkedBlockingQueue 可以指定大小,不指定大小,默认为Integer.MAX_VALUE.
当你取一个元素的时候,如果队列是空的,那么会阻塞当前线程,直到其他线程存放了数据到队列里面。
实现原理:
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
// Note: convention in all put/take/etc is to preset local var
// holding count negative to indicate failure unless set.
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly();
try {
/*
* Note that count is used in wait guard even though it is
* not protected by lock. This works because count can
* only decrease at this point (all other puts are shut
* out by lock), and we (or some other waiting put) are
* signalled if it ever changes from capacity. Similarly
* for all other uses of count in other wait guards.
*/
//如果队列已经满了 那么会一直等待其他线程调用notFull 唤醒
while (count.get() == capacity) {
notFull.await();
}
enqueue(node);
c = count.getAndIncrement();
if (c + 1 < capacity)
//通知没有满
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
//发信号 表示当前队列已经不是非空 可以使用take 取数据了
signalNotEmpty();
}
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
final AtomicInteger count = this.count;
//如果已经满了 那么直接返回
if (count.get() == capacity)
return false;
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock;
putLock.lock();
try {
if (count.get() < capacity) {
enqueue(node);
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
}
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
return c >= 0;
}
public E take() throws InterruptedException {
E x;
int c = -1;
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly();
try {
//如果当前队列数量为0 那么等待其他存放数据 放出notEmpty 信号
while (count.get() == 0) {
notEmpty.await();
}
x = dequeue();
c = count.getAndDecrement();
if (c > 1)
notEmpty.signal();
} finally {
takeLock.unlock();
}
if (c == capacity)
signalNotFull();
return x;
}