博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java实现生产者消费者模式的三种方法
阅读量:2178 次
发布时间:2019-05-01

本文共 2298 字,大约阅读时间需要 7 分钟。

  1. 前言

    生产者消费者模式是程序设计中非常常见的一种设计模式,被广泛运用在解耦、消息队列等场景。在现实世界中,我们把生产商品的一方称为生产者,把消费商品的一方称为消费者,有时生产者的生产速度特别快,但消费者的消费速度跟不上,俗称“产能过剩”,又或是多个生产者对应多个消费者时,大家可能会手忙脚乱。如何才能让大家更好地配合呢?这时在生产者和消费者之间就需要一个中介来进行调度,于是便诞生了生产者消费者模式。

  2. BlockingQueue 实现生产者消费者模式

    public static void main(String[] args) {
    BlockingQueue queue = new ArrayBlockingQueue<>(10); Runnable producer = () -> {
    while (true) {
    queue.put(new Object()); } }; new Thread(producer).start();new Thread(producer).start(); Runnable consumer = () -> {
    while (true) {
    queue.take();} };new Thread(consumer).start();new Thread(consumer).start();}
  3. Condition 实现生产者消费者模式

    public class MyBlockingQueueForCondition {
    private Queue queue; private int max = 16; private ReentrantLock lock = new ReentrantLock(); private Condition notEmpty = lock.newCondition(); private Condition notFull = lock.newCondition(); public MyBlockingQueueForCondition(int size) {
    this.max = size; queue = new LinkedList(); } public void put(Object o) throws InterruptedException {
    lock.lock(); try {
    while (queue.size() == max) {
    notFull.await(); } queue.add(o); notEmpty.signalAll(); } finally {
    lock.unlock(); } } public Object take() throws InterruptedException {
    lock.lock(); try {
    while (queue.size() == 0) {
    notEmpty.await(); } Object item = queue.remove(); notFull.signalAll(); return item; } finally {
    lock.unlock(); } }}
  4. wait/notify 实现生产者消费者模式

    class MyBlockingQueue {
    private int maxSize; private LinkedList storage; public MyBlockingQueue(int size) {
    this.maxSize = size; storage = new LinkedList<>(); } public synchronized void put() throws InterruptedException {
    while (storage.size() == maxSize) {
    wait(); } storage.add(new Object()); notifyAll(); } public synchronized void take() throws InterruptedException {
    while (storage.size() == 0) {
    wait(); } System.out.println(storage.remove()); notifyAll(); }}

转载地址:http://ckjkb.baihongyu.com/

你可能感兴趣的文章
【LEETCODE】27-Remove Element
查看>>
【LEETCODE】66-Plus One
查看>>
【LEETCODE】26-Remove Duplicates from Sorted Array
查看>>
【LEETCODE】118-Pascal's Triangle
查看>>
【LEETCODE】119-Pascal's Triangle II
查看>>
【LEETCODE】88-Merge Sorted Array
查看>>
【LEETCODE】19-Remove Nth Node From End of List
查看>>
【LEETCODE】125-Valid Palindrome
查看>>
【LEETCODE】28-Implement strStr()
查看>>
【LEETCODE】6-ZigZag Conversion
查看>>
【LEETCODE】8-String to Integer (atoi)
查看>>
【LEETCODE】14-Longest Common Prefix
查看>>
【LEETCODE】38-Count and Say
查看>>
【LEETCODE】278-First Bad Version
查看>>
【LEETCODE】303-Range Sum Query - Immutable
查看>>
【LEETCODE】21-Merge Two Sorted Lists
查看>>
【LEETCODE】231-Power of Two
查看>>
【LEETCODE】172-Factorial Trailing Zeroes
查看>>
【LEETCODE】112-Path Sum
查看>>
【LEETCODE】9-Palindrome Number
查看>>