生产者消费者的改造,生产者往队列里面去扔,消费者往队列里面去取。
阻塞队列就是你消费者去取的话如果队列为空,就等待,去取出产品。同理生产者。
这个队列支持优先级排序并且是无界的阻塞队列。
带延时功能的。
上面的是阻塞队列的方法。
只有put和take是阻塞的。
使用blockqueue可以取代的是wait和notify的。
代码:
package com.roocon.thread.tc9;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Tmall3 implements Shop {
public final int MAX_COUNT = 10;
private BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(MAX_COUNT);
public void push() {
try {
queue.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void take() {
try {
queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void size() {
while (true) {
System.out.println("当前队列的长队为:" + queue.size());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
我们可以并发的打印队列的长度:
new Thread(()->{
tmall.size();
}).start();
比较之前的condition或者是wait和notify的实现,其实阻塞队列底层就是condition或者wait和notify
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)//count是队列的长度
notFull.await();//满了就等待着
enqueue(e);
} finally {
lock.unlock();
}
}
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
items[putIndex] = x;//加在哪个下标下面
if (++putIndex == items.length)
putIndex = 0;
count++;
notEmpty.signal();//叫醒
}
/** The queued items 这个是数组 */
final Object[] items;
---
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
private E dequeue() {
// assert lock.getHoldCount() == 1;
// assert items[takeIndex] != null;
final Object[] items = this.items;
@SuppressWarnings("unchecked")
E x = (E) items[takeIndex];
items[takeIndex] = null;
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
notFull.signal();
return x;
}
--------------------------------------------------------tc9-----------------------------------------------------------------