学了生产者/消费者模式这么久,今天终于来实现一下了,写以前先复习一下生产者/消费者。java
生产者/消费者模式在操做系统中是个经典的进程同步问题,能够使用“信号量”机制来解决,须要注意的点在下面有提到。缓存
写以前先分析一下须要作的事情:ide
用LinkedHashMap当缓存,synchronized做为同步锁测试
定义一个缓存队列this
public class PublicQueue<T> {
//数据插入的下标
private int putIndex = 0;
//最大容量
private int maxCount = 50;
//缓冲区
private LinkedHashMap<Integer, T> linkedHashMap = new LinkedHashMap<>();
/** * 往阻塞队列添加数据 * @param msg */
public synchronized void put(T msg) {
//若是缓存的数据达到maxCount,阻塞
if (linkedHashMap.size() == maxCount) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//没有满,就唤醒其余全部线程
notifyAll();
}
//往缓存里面存数据
linkedHashMap.put(putIndex, msg);
System.out.println("生产一个产品,当前商品下标为:"+putIndex+"===文本为:"+msg+"===缓存长度为:"+linkedHashMap.size());
//更新putIndex
putIndex = (putIndex + 1 >= maxCount) ? (putIndex + 1) % maxCount : putIndex + 1;
}
/*** * 从阻塞队列取数据 * @return */
public synchronized T get() {
//若是阻塞队列为空,就阻塞消费者
if (linkedHashMap.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
notifyAll();
}
//经过Iterator取数据,确保取出的数据是有序的
Iterator iterator = linkedHashMap.entrySet().iterator();
T t = null;
if (iterator.hasNext()) {
Map.Entry<Integer, T> entry = (Map.Entry<Integer, T>) iterator.next();
t = entry.getValue();
int index = entry.getKey();
linkedHashMap.remove(index);
System.out.println("消费一个产品,当前商品下标为:"+index+"===文本为:"+ t +"===缓存长度为:"+linkedHashMap.size());
}
return t;
}
}
复制代码
定义一个生产者线程spa
public class Provider extends Thread{
private PublicQueue publicQueue;
public Provider(PublicQueue publicQueue) {
this.publicQueue = publicQueue;
}
@Override
public void run() {
for (int i = 0; i < 60; i++) {
publicQueue.put(String.valueOf(i));
}
}
}
复制代码
定义一个消费者线程操作系统
public class Consumer extends Thread{
private PublicQueue publicQueue;
public Consumer(PublicQueue publicQueue) {
this.publicQueue = publicQueue;
}
@Override
public void run() {
for (; ; ) {
publicQueue.get();
}
}
}
复制代码
测试线程
public class ProviderConsumerTest {
public static void main(String[] args) {
PublicQueue publicQueue = new PublicQueue();
Provider provider = new Provider(publicQueue);
Consumer consumer = new Consumer(publicQueue);
provider.start();
consumer.start();
}
}
复制代码
这个方式也是比较简单的,直接使用Java提供的阻塞队列便可code
public class PublicQueue<T> {
//缓冲区
private BlockingDeque<T> blockingDeque = new LinkedBlockingDeque<>(50);
public void add(T msg){
try {
blockingDeque.put(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产一个产品,当前商品下标为:"+"===文本为:"+msg);
}
public T get(){
T t = null;
try {
t = blockingDeque.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费一个产品,当前商品下标为:"+"===文本为:"+t);
return t;
}
}
复制代码