阻塞队列概念与基本使用
在了解阻塞队列之前我们要知道什么是队列,队列就是一个先进先出的结构,那什么是阻塞队列呢?具有阻塞功能的成为阻塞队列。
1.如果队列空,尝试出队列则阻塞等待,等待到不空为止
2.如果队列满,尝试入队列则阻塞等待,等待到不满为止
3.阻塞队列是进程安全的
多线程数据交互可以使用阻塞队列,简化代码编写。
阻塞队列核心方法有两个:put 和 take
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new LinkedBlockingQueue();
//放入三个数据,取四次看效果
queue.put("hello");
queue.put("hello");
queue.put("hello");
String str = queue.take();
System.out.println(str);
str = queue.take();
System.out.println(str);
str = queue.take();
System.out.println(str);
str = queue.take();
System.out.println(str);
//此时我们发现取第四次程序不会结束,而是阻塞等待
}
生产者消费者模型
生产者和消费者是服务器常见的代码写法,生产者放数据,消费者取数据。
生产者消费者初心是什么?
可以让上下游模块之间,更好的“解耦合”,
什么叫耦合?
两个模块之间关联性强还是弱,关联性强,耦合越高。
什么是高内聚低耦合?
低耦合:两个模块之间关联性小,称为低耦合。
高内聚:相关联的代码分门别类规制起来,称为高内聚。
写代码要追求高内聚低耦合,避免代码牵一发动全身。
上图直接通信,耦合度高
上图没直接通信采用阻塞队列,耦合度低。
阻塞队列削峰填谷
阻塞队列作用:A收到来自用户的请求,有时会有峰值可以削峰填谷的作用,如果没使用阻塞队列,采用直接通信B也会有这个峰值,B也就挂了,服务器处理每个请求,都要需要消耗资源。采用阻塞队列就大大降低了,A收到请求多了,B不会有峰值影响,仍然按照之前的速率取元素。
代码实现生产者消费者模型
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> queue = new LinkedBlockingQueue();
Thread t1 = new Thread(() -> {
while (true) {
try {
int val = queue.take();
System.out.println("消费" + val);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
Thread t2 = new Thread(() -> {
int val = 0;
while (true) {
System.out.println("生产" + val);
try {
queue.put(val++);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t2.start();
}
模拟实现阻塞队列
class MyBlockingQueue {
private int[] elem = new int[1000];
// [head,tail)区间
private int head;//头
private int tail;//尾
private int usedSize;//记录元素个数
Object obj = new Object();
synchronized public void put(int val) throws InterruptedException {
while (usedSize == elem.length) {//wait会被interrupt中断所以需要使用while循环,保证条件满足
this.wait();//满了,阻塞等待
}
elem[tail] = val;//放入元素
tail++;//放完元素,++后移
if (tail == elem.length) {//到末尾,让tail从头再来
tail = 0;
}
usedSize++;
this.notify();//唤醒take方法
}
synchronized public Integer take() throws InterruptedException {
//出队列
while (usedSize == 0) {//wait会被interrupt中断所以需要使用while循环,保证条件满足
this.wait();
}
int val = elem[head];//取head位置元素
head++;//向前移动
if (head == elem.length) {//到头了,从0开始。
head = 0;
}
usedSize--;//取出一个值,us--;
this.notify();//唤醒put的wait方法
return val;
}
}