双端队列BlockingDeque可以实现FIFO与FILO的操作,BlockingDeque只有一个实现子类:
- LinkedBlockingDeque
1、使用双端阻塞队列实现生产者与消费者模型的例子:
package com.mydemo;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
public class JUCDemo {
public static void main(String[] args) {
// 双端阻塞队列
BlockingDeque<String> blockingDeque = new LinkedBlockingDeque<>();
// 循环创建线程---生产者线程
for(int i = 0; i < 10; i++){
if(i%2 == 0){
new Thread(()->{
for(int j = 0; j < 5; j++){
try {
// 延迟操作
TimeUnit.SECONDS.sleep(2);
String msg = "【" + Thread.currentThread().getName() + "】生产的数据:" + j;
// 首部保存
blockingDeque.putFirst(msg);
System.out.println("{生产数据}" + msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "FIRST生产者线程-" + i).start();
}else{
new Thread(()->{
for(int j = 0; j < 5; j++){
try {
// 延迟操作
TimeUnit.SECONDS.sleep(2);
String msg = "【" + Thread.currentThread().getName() + "】生产的数据:" + j;
// 尾部保存
blockingDeque.putLast(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "LAST生产者线程-" + i).start();
}
}
// 消费者线程
for(int i = 0; i < 2; i++){
new Thread(()->{
int count = 0;
while (true){
try {
// 延迟操作
TimeUnit.SECONDS.sleep(2);
if(count%2==0){
// 首部取出
System.err.println("FIRST取出" + blockingDeque.takeFirst());
}else{
// 尾部取出
System.err.println("LAST取出" + blockingDeque.takeLast());
}
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "消费者线程-" + i).start();
}
}
}