BlockingDeque是一个阻塞有界的链表结构。
对它添加数据或者对他弹出数据,都是阻塞的,因为是有界的,所以我们添加的时候,如果已经达到了容量,他就会等待。
弹出队列也是一样,如果里面没有元素了,弹出的时候就会被阻塞。
下面上代码:
生产者代码
class Producer extends Thread {
private String name;
private BlockingDeque<Integer> appleBox;
private AtomicInteger appleCurrentNum;
private Boolean flag = true;
Producer(String name, BlockingDeque<Integer> appleBox, AtomicInteger appleCurrentNum) {
this.name = name;
this.appleBox = appleBox;
this.appleCurrentNum = appleCurrentNum;
}
@Override
public void run() {
while (flag) {
int apple = appleCurrentNum.addAndGet(1);
Integer thePutElement;
try {
boolean isOffer = appleBox.offer(apple,2, TimeUnit.SECONDS);
if (isOffer){
System.out.println("[ " + name + " 生产者 线程:" +this.getName() + " ] 生产了编号为-" + apple + "-号苹果,当前苹果有:" + appleBox + "");
} else{
System.out.println("[ " + name +" 生产者 线程 "+ this.getName() + " ] 正在生产苹果 ,但是队列已满等待消费者消费,当前苹果有:" + appleBox +"");
}
Thread.sleep(new Random().nextInt(1000));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void shutdownThread(){
this.flag = false;
}
}
消费者的代码:
class Producer extends Thread {
private String name;
private BlockingDeque<Integer> appleBox;
private AtomicInteger appleCurrentNum;
private Boolean flag = true;
Producer(String name, BlockingDeque<Integer> appleBox, AtomicInteger appleCurrentNum) {
this.name = name;
this.appleBox = appleBox;
this.appleCurrentNum = appleCurrentNum;
}
@Override
public void run() {
while (flag) {
int apple = appleCurrentNum.addAndGet(1);
Integer thePutElement;
try {
boolean isOffer = appleBox.offer(apple,2, TimeUnit.SECONDS);
if (isOffer){
System.out.println("[ " + name + " 生产者 线程:" +this.getName() + " ] 生产了编号为-" + apple + "-号苹果,当前苹果有:" + appleBox + "");
} else{
System.out.println("[ " + name +" 生产者 线程 "+ this.getName() + " ] 正在生产苹果 ,但是队列已满等待消费者消费,当前苹果有:" + appleBox +"");
}
Thread.sleep(new Random().nextInt(1000));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void shutdownThread(){
this.flag = false;
}
}
测试代码:
public class CAndPTest {
public static final Integer initBoxSize = 5;
public static void main(String[] args) {
BlockingDeque<Integer> appleBox = new LinkedBlockingDeque<>(5);
AtomicInteger initNum = new AtomicInteger(0);
List<Producer> producers = new ArrayList<>(3);
List<Consumer> consumers = new ArrayList<>(3);
for (int i = 0 ; i< 3 ;i++){
Producer producer = new Producer("P_1",appleBox,initNum);
producers.add(producer);
producer.start();
Consumer consumer = new Consumer("C_1",appleBox);
consumers.add(consumer);
consumer.start();
}
// 让生产者和消费者运行10秒钟。
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0 ; i < 3 ;i++){
producers.get(i).shutdownThread();
consumers.get(i).shutdownThread();
}
}
}