生产者消费者模型
在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程。在多线程开发当中,如果生产者处理速度很快,而消费者处理速度很慢,那么生产者就必须等待消费者处理完,才能继续生产数据。同样的道理,如果消费者的处理能力大于生产者,那么消费者就必须等待生产者。为了解决这种生产消费能力不均衡的问题,所以便有了生产者和消费者模式。
生产者消费者模式是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列里取,阻塞队列就相当于一个缓冲区,平衡了生产者和消费者的处理能力。这个阻塞队列就是用来给生产者和消费者解耦的。
直接上代码,看看生产者消费者模式应该怎么实现。
/**
* 生产者消费者模式:使用Object.wait() / notify()方法实现
*/
public class ProducerConsumer {
private static final int CAPACITY = 5;
public static void main(String args[]){
Queue queue = new LinkedList();
Thread producer1 = new Producer("P-1", queue, CAPACITY);
Thread producer2 = new Producer("P-2", queue, CAPACITY);
Thread consumer1 = new Consumer("C1", queue, CAPACITY);
Thread consumer2 = new Consumer("C2", queue, CAPACITY);
Thread consumer3 = new Consumer("C3", queue, CAPACITY);
producer1.start();
producer2.start();
consumer1.start();
consumer2.start();
consumer3.start();
}
/**
* 生产者
*/
public static class Producer extends Thread{
private Queue queue;
String name;
int maxSize;
int i = 0;
public Producer(String name, Queue queue, int maxSize){
super(name);
this.name = name;
this.queue = queue;
this.maxSize = maxSize;
}
@Override
public void run(){
while(true){//加上个死循环,生产者消费者线程可以一直不停工作,要不然进行一次操作就结束了
synchronized(queue){
while(queue.size() == maxSize){
try {
System.out .println("Queue is full, Producer[" + name + "] thread waiting for " +
"consumer to take something from queue.");
queue.wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("[" + name + "] Producing value : +" + i);
queue.offer(i++);
queue.notifyAll();
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 消费者
*/
public static class Consumer extends Thread{
private Queue queue;
String name;
int maxSize;
public Consumer(String name, Queue queue, int maxSize){
super(name);
this.name = name;
this.queue = queue;
this.maxSize = maxSize;
}
@Override
public void run(){
while(true){
synchronized(queue){
while(queue.isEmpty()){
try {
System.out.println("Queue is empty, Consumer[" + name + "] thread is waiting for Producer");
queue.wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
int x = queue.poll();
System.out.println("[" + name + "] Consuming value : " + x);
queue.notifyAll();
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static class Producer implements Runnable {
int i;
LinkedList queue;
int max;
ReentrantLock lock;
Condition fullCondition;
Condition emptyCondition;
public Producer(LinkedList queue, int max, ReentrantLock lock,
Condition fullCondition, Condition emptyCondition) {
this.queue = queue;
this.max = max;
this.lock = lock;
this.fullCondition = fullCondition;
this.emptyCondition = emptyCondition;
}
public void run() {
while (true) {
lock.lock();
try {
while (queue.size() == max) {
fullCondition.await();
}
queue.add(i++);
System.out.println(Thread.currentThread().getName()
+ " produce " + queue.size());
emptyCondition.signalAll();
fullCondition.signalAll();
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
public static class Consumer implements Runnable {
LinkedList queue;
int max;
ReentrantLock lock;
Condition fullCondition;
Condition emptyCondition;
public Consumer(LinkedList queue, int max, ReentrantLock lock,
Condition fullCondition, Condition emptyCondition) {
this.queue = queue;
this.max = max;
this.lock = lock;
this.fullCondition = fullCondition;
this.emptyCondition = emptyCondition;
}
public void run() {
while (true) {
lock.lock();
try {
while (queue.isEmpty()) {
emptyCondition.await();
}
queue.poll();
System.out.println(Thread.currentThread().getName()
+ " consume " + queue.size());
fullCondition.signalAll();
emptyCondition.signalAll();
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList<>();
ReentrantLock lock = new ReentrantLock();
Condition full = lock.newCondition();
Condition empty = lock.newCondition();
for (int i = 0; i < 3; i++) {
new Thread(new Producer(list, 3, lock, full, empty), "produce" + i)
.start();
new Thread(new Consumer(list, 3, lock, full, empty), "consume" + i)
.start();
}
}
/**
* 生产者消费者模式:使用Lock和Condition实现
* {@link java.util.concurrent.locks.Lock}
* {@link java.util.concurrent.locks.Condition}
*/
public class ProducerConsumerByLock {
private static final int CAPACITY = 5;
private static final Lock lock = new ReentrantLock();
private static final Condition fullCondition = lock.newCondition(); //队列满的条件
private static final Condition emptyCondition = lock.newCondition(); //队列空的条件
public static void main(String args[]){
Queue queue = new LinkedList();
Thread producer1 = new Producer("P-1", queue, CAPACITY);
Thread producer2 = new Producer("P-2", queue, CAPACITY);
Thread consumer1 = new Consumer("C1", queue, CAPACITY);
Thread consumer2 = new Consumer("C2", queue, CAPACITY);
Thread consumer3 = new Consumer("C3", queue, CAPACITY);
producer1.start();
producer2.start();
consumer1.start();
consumer2.start();
consumer3.start();
}
/**
* 生产者
*/
public static class Producer extends Thread{
private Queue queue;
String name;
int maxSize;
int i = 0;
public Producer(String name, Queue queue, int maxSize){
super(name);
this.name = name;
this.queue = queue;
this.maxSize = maxSize;
}
@Override
public void run(){
while(true){
//获得锁
lock.lock();
while(queue.size() == maxSize){
try {
System.out .println("Queue is full, Producer[" + name + "] thread waiting for " +
"consumer to take something from queue.");
//条件不满足,生产阻塞
fullCondition.await();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
System.out.println("[" + name + "] Producing value : +" + i);
queue.offer(i++);
//唤醒其他所有生产者、消费者
fullCondition.signalAll();
emptyCondition.signalAll();
//释放锁
lock.unlock();
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 消费者
*/
public static class Consumer extends Thread{
private Queue queue;
String name;
int maxSize;
public Consumer(String name, Queue queue, int maxSize){
super(name);
this.name = name;
this.queue = queue;
this.maxSize = maxSize;
}
@Override
public void run(){
while(true){
//获得锁
lock.lock();
while(queue.isEmpty()){
try {
System.out.println("Queue is empty, Consumer[" + name + "] thread is waiting for Producer");
//条件不满足,消费阻塞
emptyCondition.await();
} catch (Exception ex) {
ex.printStackTrace();
}
}
int x = queue.poll();
System.out.println("[" + name + "] Consuming value : " + x);
//唤醒其他所有生产者、消费者
fullCondition.signalAll();
emptyCondition.signalAll();
//释放锁
lock.unlock();
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
JDK 1.5 以后新增的 java.util.concurrent
包新增了 BlockingQueue
接口。并提供了如下几种阻塞队列实现:
ArrayBlockingQueue:ArrayBlockingQueue 是一个有界的阻塞队列,其内部实现是将对象放到一个数组里。有界也就意味着,它不能够存储无限多数量的元素。它有一个同一时间能够存储元素数量的上限。你可以在对其初始化的时候设定这个上限,但之后就无法对这个上限进行修改了(译者注:因为它是基于数组实现的,也就具有数组的特性:一旦初始化,大小就无法修改)。
DelayQueue:DelayQueue 对元素进行持有直到一个特定的延迟到期。注入其中的元素必须实现 java.util.concurrent.Delayed 接口。
LinkedBlockingQueue:LinkedBlockingQueue 内部以一个链式结构(链接节点)对其元素进行存储。如果需要的话,这一链式结构可以选择一个上限。如果没有定义上限,将使用 Integer.MAX_VALUE 作为上限。
PriorityBlockingQueue:PriorityBlockingQueue 是一个无界的并发队列。它使用了和类 java.util.PriorityQueue 一样的排序规则。你无法向这个队列中插入 null 值。所有插入到 PriorityBlockingQueue 的元素必须实现 java.lang.Comparable 接口。因此该队列中元素的排序就取决于你自己的 Comparable 实现。
SynchronousQueue:SynchronousQueue 是一个特殊的队列,它的内部同时只能够容纳单个元素。如果该队列已有一元素的话,试图向队列中插入一个新元素的线程将会阻塞,直到另一个线程将该元素从队列中抽走。同样,如果该队列为空,试图向队列中抽取一个元素的线程将会阻塞,直到另一个线程向队列中插入了一条新的元素。据此,把这个类称作一个队列显然是夸大其词了。它更多像是一个汇合点。
实现生产者-消费者模型使用 ArrayBlockingQueue
或者 LinkedBlockingQueue
即可。
BlockingQueue 具有 4 组不同的方法用于插入、移除以及对队列中的元素进行检查。如果请求的操作不能得到立即执行的话,每个方法的表现也不同。这些方法如下:
四组不同的行为方式解释:
无法向一个 BlockingQueue 中插入 null。如果你试图插入 null,BlockingQueue 将会抛出一个 NullPointerException。
可以访问到 BlockingQueue 中的所有元素,而不仅仅是开始和结束的元素。比如说,你将一个对象放入队列之中以等待处理,但你的应用想要将其取消掉。那么你可以调用诸如 remove(o) 方法来将队列之中的特定对象进行移除。但是这么干效率并不高(译者注:基于队列的数据结构,获取除开始或结束位置的其他对象的效率不会太高),因此你尽量不要用这一类的方法,除非你确实不得不那么做。
我们这里使用LinkedBlockingQueue
,它是一个已经在内部实现了同步的队列,实现方式采用的是我们第2种await()
/ signal()
方法。它可以在生成对象时指定容量大小。它用于阻塞操作的是put()和take()方法。
put()
方法:类似于我们上面的生产者线程,容量达到最大时,自动阻塞。take()
方法:类似于我们上面的消费者线程,容量为0时,自动阻塞。/**
* 生产者消费者模式:使用{@link java.util.concurrent.BlockingQueue}实现
*/
public class ProducerConsumerByBQ{
private static final int CAPACITY = 5;
public static void main(String args[]){
LinkedBlockingDeque blockingQueue = new LinkedBlockingDeque(CAPACITY);
Thread producer1 = new Producer("P-1", blockingQueue, CAPACITY);
Thread producer2 = new Producer("P-2", blockingQueue, CAPACITY);
Thread consumer1 = new Consumer("C1", blockingQueue, CAPACITY);
Thread consumer2 = new Consumer("C2", blockingQueue, CAPACITY);
Thread consumer3 = new Consumer("C3", blockingQueue, CAPACITY);
producer1.start();
producer2.start();
consumer1.start();
consumer2.start();
consumer3.start();
}
/**
* 生产者
*/
public static class Producer extends Thread{
private LinkedBlockingDeque blockingQueue;
String name;
int maxSize;
int i = 0;
public Producer(String name, LinkedBlockingDeque queue, int maxSize){
super(name);
this.name = name;
this.blockingQueue = queue;
this.maxSize = maxSize;
}
@Override
public void run(){
while(true){
try {
blockingQueue.put(i);
System.out.println("[" + name + "] Producing value : +" + i);
i++;
//暂停最多1秒
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 消费者
*/
public static class Consumer extends Thread{
private LinkedBlockingDeque blockingQueue;
String name;
int maxSize;
public Consumer(String name, LinkedBlockingDeque queue, int maxSize){
super(name);
this.name = name;
this.blockingQueue = queue;
this.maxSize = maxSize;
}
@Override
public void run(){
while(true){
try {
int x = blockingQueue.take();
System.out.println("[" + name + "] Consuming : " + x);
//暂停最多1秒
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
除了这几种之外还有其他的方式,在说一个使用信号量Semaphore的方式,因为信号量可以控制线程进入临界区,达到同步的效果。
public class TestSemaphore {
public static void main(String[] args) {
// 启动线程
for (int i = 0; i <= 3; i++) {
// 生产者
new Thread(new Producer()).start();
// 消费者
new Thread(new Consumer()).start();
}
}
// 仓库
static Warehouse buffer = new Warehouse();
// 生产者,负责增加
static class Producer implements Runnable {
static int num = 1;
@Override
public void run() {
int n = num++;
while (true) {
try {
buffer.put(n);
System.out.println(">" + n);
// 速度较快。休息10毫秒
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 消费者,负责减少
static class Consumer implements Runnable {
@Override
public void run() {
while (true) {
try {
System.out.println("<" + buffer.take());
// 速度较慢,休息1000毫秒
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 仓库
*
* @author 老紫竹(laozizhu.com)
*/
static class Warehouse {
// 非满锁 ,控制生产者线程
final Semaphore notFull = new Semaphore(10);
// 非空锁 ,控制消费者线程
final Semaphore notEmpty = new Semaphore(0);
// 核心锁 ,控制每次只能有一个线程进入临界区
final Semaphore mutex = new Semaphore(1);
// 库存容量
final Object[] items = new Object[10];
int putptr, takeptr, count;
/**
* 把商品放入仓库.
*
* @param x
* @throws InterruptedException
*/
public void put(Object x) throws InterruptedException {
// 保证非满
notFull.acquire();
// 保证不冲突
mutex.acquire();
try {
// 增加库存
items[putptr] = x;
if (++putptr == items.length)
putptr = 0;
++count;
} finally {
// 退出核心区
mutex.release();
// 增加非空信号量,允许获取商品
notEmpty.release();
}
}
/**
* 从仓库获取商品
*
* @return
* @throws InterruptedException
*/
public Object take() throws InterruptedException {
// 保证非空
notEmpty.acquire();
// 核心区
mutex.acquire();
try {
// 减少库存
Object x = items[takeptr];
if (++takeptr == items.length)
takeptr = 0;
--count;
return x;
} finally {
// 退出核心区
mutex.release();
// 增加非满的信号量,允许加入商品
notFull.release();
}
}
}
}