一、简述
1️⃣生产者消费者模式并不是 GOF 提出的 23 种设计模式之一,23 种设计模式都是建立在面向对象的基础之上的,但其实面向过程的编程中也有很多高效的编程模式,生产者消费者模式便是其中之一,它是编程过程中最常用的一种设计模式。
一个常见的场景:某个模块负责产生数据,这些数据由另一个模块来负责处理(此处的模块是广义的,可以是类、函数、线程、进程等)。产生数据的模块,就形象地称为生产者;而处理数据的模块,就称为消费者。单单抽象出生产者和消费者,还够不上是生产者/消费者模式。该模式还需要有一个缓冲区处于生产者和消费者之间,作为一个中介。生产者把数据放入缓冲区,而消费者从缓冲区取出数据。
2️⃣举个寄信的例子,大致过程如下:
- 把信写好——相当于生产者制造数据。
- 把信放入邮筒——相当于生产者把数据放入缓冲区。
- 邮递员把信从邮筒取出——相当于消费者把数据取出缓冲区。
- 邮递员把信拿去邮局做相应的处理——相当于消费者处理数据。
3️⃣说明
- 生产消费者模式可以有效的对数据解耦,优化系统结构。
- 降低生产者和消费者线程相互之间的依赖与性能要求。
- 一般使用 BlockingQueue 作为数据缓冲队列,是通过锁和阻塞来实现数据之间的同步。如果对缓冲队列有性能要求,则可以使用基于 CAS 无锁设计的 ConcurrentLinkedQueue。
二、生产者-消费者模式是一个经典的多线程设计模式
【生产者-消费者模式】为多线程间的协作提供了良好的解决方案。在该模式中,通常有两类线程,即若干个生产者线程和若干个消费者线程。生产者线程负责提交用户请求,消费者线程则负责具体处理生产者提交的任务。生产者和消费者之间则通过共享内存缓冲区进行通信,其结构图如:![](https://img.haomeiwen.com/i7038163/8e2468e9fe057f70.jpg)
PCData 是需要处理的元数据模型,生产者构建 PCData,并放入缓冲队列。消费者从缓冲队列中获取数据,并执行计算。
1️⃣生产者核心代码:
while (isRunning) {
Thread.sleep(r.nextInt(SLEEP_TIME));
data = new PCData(count.incrementAndGet);
// 构造任务数据
System.out.println(data + " is put into queue");
if (!queue.offer(data, 2, TimeUnit.SECONDS)) {
// 将数据放入队列缓冲区中
System.out.println("faild to put data : " + data);
}
}
2️⃣消费者核心代码:
while (true) {
PCData data = queue.take();
// 提取任务
if (data != null) {
// 获取数据, 执行计算操作
int re = data.getData() * 10;
System.out.println("after cal, value is : " + re);
Thread.sleep(r.nextInt(SLEEP_TIME));
}
}
三、详细逻辑
生产者不断的往仓库中生产货物,货物装满时等消费者消费再生产。消费者不断的从仓库中消费货物,仓库为空时等生产者生产后再消费。即:线程 A 向队列 Q 中不停写入数据,线程 B 从队列 Q 中不停读取数据(只要 Q 中有数据)
1️⃣定义接口以及接口的实现类
接口包含两个方法:一个是向队列中写 push();一个是从队列中读 pop()。
public interface StackInterface {
void push(int n);
int[] pop();
}
实现类
public class SafeStackImpl implements StackInterface {
private int top = 0;
private int[] values = new int[10];
private boolean dataAvailable = false;
public void push(int n) {
synchronized (this) {
while (dataAvailable) {
try {
wait();
} catch (InterruptedException e) {
}
}
values[top] = n;
System.out.println("压入数字" + n + "步骤1完成");
top++;
dataAvailable = true;
notifyAll();
System.out.println("压入数字完成");
}
}
public int[] pop() {
synchronized (this) {
while (!dataAvailable) {
try {
wait();
} catch (InterruptedException e) {
}
}
System.out.println("弹出");
top--;
int[] test = {values[top], top};
dataAvailable = false;
//唤醒正在等待压入数据的线程
notifyAll();
return test;
}
}
}
2️⃣实际应用
写线程
public class PushThread implements Runnable {
private StackInterface s;
public PushThread(StackInterface s) {
this.s = s;
}
public void run() {
int i = 0;
while (true) {
java.util.Random r = new java.util.Random();
i = r.nextInt(10);
s.push(i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
}
读线程
public class PopThread implements Runnable {
private StackInterface s;
public PopThread(StackInterface s) {
this.s = s;
}
public void run() {
while (true) {
System.out.println("-->" + s.pop()[0] + "<--");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
}
网友评论