這個模式大部分都是用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("消費停止");
}
}
}