天天看点

java消费者生产者设计模式_设计模式之生产者消费者模式

这个模式大部分都是用MQ(message queue 消息队列)在实际生产过程中实现的

要实现这个设计模式,就需要

原料:多个生产者线程生产商品(类比为list的add),多个消费者消费商品(类比为list的remove),商品的库存(一个同步的共享变量,list)

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 queue = new LinkedBlockingQueue(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("消费停止");

}

}

}