这个模式大部分都是用MQ(message queue 消息队列)在实际生产过程中实现的
要实现这个设计模式,就需要
原料:多个生产者线程生产商品(类比为list的add),多个消费者消费商品(类比为list的remove),商品的库存(一个同步的共享变量,list)
实现:多个生产者在生产商品 并把商品都放到仓库(queue,有最大容量)中,多个消费者要去时不时的看看有没有多的商品 就买走,这里也要注意到多线程的一致性。否则将会出现 商品数量为负数的情况,所以 生产和消费要是同步的。
package design_pattern;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 生产者消费者模式 多线程生产消费 实现一个 笔试题
*/
public class ProducterAndConsumer {
public static void main(String[] args) throws InterruptedException {
//此处的商品不用list 而用juc包中的 线形阻塞队列来实现
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10);
ProducerThread p1 = new ProducerThread(queue);
ProducerThread p2 = new ProducerThread(queue);
ConsumerThread c = new ConsumerThread(queue);
p1.start();
p2.start();
c.start();
// 执行10秒
Thread.sleep(10 * 1000);
p1.stopThread();
p2.stopThread();
}
}
class ProducerThread extends Thread {
private BlockingQueue queue;
private boolean flag = true;
// 原子类变量,此处用juc的原子类来记录 生产和消费的编号
public static AtomicInteger count = new AtomicInteger();
public ProducerThread(BlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("生产线程启动");
while (flag) {
System.out.println("正在生产者队列");
String data = count.incrementAndGet() + "";
// 添加队列
boolean offer = queue.offer(data);
String msg = null;
if (offer) {
msg = Thread.currentThread().getName()+"生产者生产" + data + "成功";
} else {
msg = "生产者生产" + data + "失败";
}
System.out.println(msg);
Thread.sleep(1000);
}
} catch (Exception e) {
} finally {
System.out.println("生产者线程停止");
}
}
public void stopThread() {
flag = false;
}
}
class ConsumerThread extends Thread {
private BlockingQueue queue;
private boolean flag = true;
public ConsumerThread(BlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
System.out.println("消费者线程进行消费");
try {
while (flag) {
// 获取完毕,队列删除掉用poll方法获取
String data = (String) queue.poll(2, TimeUnit.SECONDS);
if (null != data) {
System.out.println("消费者消费" + data + "成功");
} else {
System.out.println("消费者消费" + data + "失败");
this.flag=false;
}
}
} catch (Exception e) {
} finally {
System.out.println("消费停止");
}
}
}