在线程的世界中,生产者是生产数据,消费者是使用数据,不过它们生产和消费的速度不一定一致,如果有一个设计模式可以使它们生产和消费的速度一致,这种模式就是将生产者和消费者进行解耦,使生产和消费更加的顺畅。
什么是生产者和消费者模式
生产者和消费者会使用一个容器(storage),一般是阻塞队列,来解决它们的耦合问题
当生产者或者是消费者成产过量或者取空,就会停止生产或消费
当生产者生产时会通知消费者进行消费,当消费者没有数据消耗时会通知生产者进行生产
模式代码//用wait/notify来实现
import java.util.ArrayList;
import java.util.Date;
import java.util.linkedList;
import java.util.List;
public class ProducerConsumerModel {
public static void main(String[] args) {
EventStorage eventStorage = new EventStorage();
Producer producer = new Producer(eventStorage);
Consumer consumer = new Consumer(eventStorage);
new Thread(producer).start();
new Thread(consumer).start();
}
//生产类
static class Producer implements Runnable {
private EventStorage storage;
public Producer(EventStorage storage) {
this.storage = storage;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
storage.put();
}
}
}
//消费类
static class Consumer implements Runnable {
private EventStorage storage;
public Consumer(EventStorage storage) {
this.storage = storage;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
storage.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class EventStorage {
private int maxSize;
//存储库
private linkedList storage;
public EventStorage() {
maxSize = 10;
storage = new linkedList() {
};
}
//生产者使用方法
public synchronized void put() {
//如果生产者已经满了,等待
while (storage.size() == maxSize) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//没有满就加入
storage.add(new Date());
System.out.println("仓库里面有了" + storage.size()
+ "个产品");
//唤醒等待线程
notify();
}
//消费者使用方法
public synchronized void take() throws InterruptedException {
//消费者取空情况
while (storage.size() == 0) {
wait();
}
//poll方法拿到并删除
System.out.println("拿到了" + storage.poll() + "现在仓库还剩下" + storage.size());
notify();
}
}
}
产出结果
结果可以看出,不是一定生产十个消耗十个,也可能是在消耗了部分数据之后就接着生产补充



