我是少侠露飞。学习塑造人生,技术改变世界。
前言
生产者-消费者模式是一个十分经典的多线程并发协作的模式,弄懂生产者-消费者问题能够让我们对并发编程的理解加深。所谓生产者-消费者问题,实际上主要是包含了两类线程,一种是生产者线程用于生产数据,另一种是消费者线程用于消费数据,为了解耦生产者和消费者的关系,通常会有一个共享的数据区域,就像是一个仓库,生产者生产数据之后直接放置在共享数据区中,并不需要关心消费者的行为;而消费者只需要从共享数据区中去获取数据,就不再需要关心生产者的行为。但是,这个共享数据区域中应该具备这样的线程间并发协作的功能:
- 如果共享数据区已满的话,阻塞生产者继续生产数据放置入内;
- 如果共享数据区为空的话,阻塞消费者继续消费数据;
在实现生产者消费者问题时,可以采用三种方式:
- 基于Object的wait/notify的消息通知机制。
- 基于ReentrantLock 和Condition的await/signal的消息通知机制。
- 基于BlockingQueue实现。
本文主要将对后两种实现方式进行总结归纳。
通过ReentrantLock 和Condition的await/signalAll机制实现
参照Object的wait和notify/notifyAll方法,Condition也提供了同样的方法:
针对wait方法
void await() throws InterruptedException
:当前线程进入等待状态,如果其他线程调用condition的signal或者signalAll方法并且当前线程获取Lock从await方法返回,如果在等待状态中被中断会抛出被中断异常;
long awaitNanos(long nanosTimeout)
:当前线程进入等待状态直到被通知,中断或者超时;
boolean await(long time, TimeUnit unit) throws InterruptedException
:同第二种,支持自定义时间单位
boolean awaitUntil(Date deadline) throws InterruptedException
:当前线程进入等待状态直到被通知,中断或者到了某个时间
针对notify方法
void signal()
:唤醒一个等待在Condition上的线程,将该线程从等待队列中转移到同步队列中,如果在同步队列中能够竞争到Lock则可以从等待方法中返回。
void signalAll()
:与signal的区别在于能够唤醒所有等待在Condition上的线程。
public class Main {
private static final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("Main-%d").build();
private static final ExecutorService executorService = new ThreadPoolExecutor(10, 10, 100L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy());
private static ReentrantLock lock = new ReentrantLock();
private static Condition full = lock.newCondition();
private static Condition empty = lock.newCondition();
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
for (int i = 0; i < 5; i++) {
executorService.submit(new Producer(linkedList, 8, lock));
}
for (int i = 0; i < 5; i++) {
executorService.submit(new Consumer(linkedList, lock));
}
}
static class Producer implements Runnable {
private List<Integer> list;
private int maxSize;
private Lock lock;
public Producer(List list, int maxSize, Lock lock) {
this.list = list;
this.maxSize = maxSize;
this.lock = lock;
}
@Override
public void run() {
for (; ; ) {
lock.lock();
try {
while (list.size() >= maxSize) {
System.out.println("Producer " + Thread.currentThread().getName() + " has reached maximum size!");
full.await();
}
Random random = new Random();
Integer element = random.nextInt();
list.add(element);
System.out.println("Producer " + Thread.currentThread().getName() + " produce message:" + element);
empty.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
static class Consumer implements Runnable {
private List<Integer> list;
private Lock lock;
public Consumer(List list, Lock lock) {
this.list = list;
this.lock = lock;
}
@Override
public void run() {
for (; ; ) {
lock.lock();
try {
while (list.isEmpty()) {
System.out.println("Consumer " + Thread.currentThread().getName() + " unable get message from empty queue!");
empty.await();
}
Integer element = list.remove(0);
System.out.println("Consumer " + Thread.currentThread().getName() + " consume message:" + element);
full.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
}
通过BlockingQueue实现
由于BlockingQueue内部实现就附加了两个阻塞操作。即当队列已满时,阻塞向队列中插入数据的线程,直至队列中未满;当队列为空时,阻塞从队列中获取数据的线程,直至队列非空时为止。可以利用BlockingQueue实现生产者-消费者为题,阻塞队列完全可以充当共享数据区域,就可以很好的完成生产者和消费者线程之间的协作。
public class Main {
private static final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("Main-%d").build();
private static final ExecutorService executorService = new ThreadPoolExecutor(10, 10, 100L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy());
private static LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
executorService.submit(new Producer(queue));
}
for (int i = 0; i < 5; i++) {
executorService.submit(new Consumer(queue));
}
}
static class Producer implements Runnable {
private BlockingQueue queue;
public Producer(BlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (; ; ) {
Random random = new Random();
int element = random.nextInt();
System.out.println("Producer " + Thread.currentThread().getName() + " produce message:" + element);
queue.put(element);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Consumer implements Runnable {
private BlockingQueue queue;
public Consumer(BlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (; ; ) {
Integer element = (Integer) queue.take();
System.out.println("Consumer " + Thread.currentThread().getName() + " consume message:" + element);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/13480.html