【Java多线程手写代码】(五):如何优雅的实现生产者、消费者

我是少侠露飞。学习塑造人生,技术改变世界。

前言

生产者-消费者模式是一个十分经典的多线程并发协作的模式,弄懂生产者-消费者问题能够让我们对并发编程的理解加深。所谓生产者-消费者问题,实际上主要是包含了两类线程,一种是生产者线程用于生产数据,另一种是消费者线程用于消费数据,为了解耦生产者和消费者的关系,通常会有一个共享的数据区域,就像是一个仓库,生产者生产数据之后直接放置在共享数据区中,并不需要关心消费者的行为;而消费者只需要从共享数据区中去获取数据,就不再需要关心生产者的行为。但是,这个共享数据区域中应该具备这样的线程间并发协作的功能:

  1. 如果共享数据区已满的话,阻塞生产者继续生产数据放置入内;
  2. 如果共享数据区为空的话,阻塞消费者继续消费数据;

在实现生产者消费者问题时,可以采用三种方式:

  • 基于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();
            }
        }
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值