(七)Producer-Consumer模式

一、定义

Producer-Consumer Pattern就是生产者-消费者模式。

生产者和消费者为不同的处理线程,生产者必须将数据安全地交给消费者,消费者进行消费时,如果生产者还没有建立数据,则消费者需要等待。

一般来说,可能存在多个生产者和消费者,不过也有可能生产者和消费者都只有一个,当双方都只有一个时,我们也称之为Pipe Pattern。

 

 

二、模式案例

该案例中,定义了三个角色:厨师、客人、桌子。

//桌子(队列)定义
public class Table {
    private final String[] buffer;
    private int tail;
    private int head;
    private int count;

    public Table(int count) {
        this.buffer = new String[count];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
    }

    public synchronized void put(String cake) throws InterruptedException {
        System.out.println(Thread.currentThread().getName()+" puts "+cake);
        while(count>=buffer.length){
            wait();
        }
        buffer[tail] = cake;
        tail = (tail+1)%buffer.length;
        count++;
        notifyAll();
    }

    public synchronized String take() throws InterruptedException {
        while(count<=0){
            wait();
        }
        String cake = buffer[head];
        head = (head+1)%buffer.length;
        count--;
        notifyAll();
        System.out.println(Thread.currentThread().getName()+" takes "+cake);
        return cake;
    }
}
//厨师(生产者)定义
public class MakerThread extends Thread {
    private final Random random;
    private final Table table;
    private static int id = 0; //蛋糕的流水号(所有厨师共通)

    public MakerThread(String name,Table table,long seed) {
        super(name);
        this.table = table;
        this.random = new Random(seed);
    }

    @Override
    public void run() {
        while(true){
            try {
                Thread.sleep(random.nextInt(1000));
                String cake = "[ Cake No."+nextId()+" by "+getName()+" ]";
                table.put(cake);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static synchronized int nextId() {
        return id++;
    }
}
//客人(消费者)定义
public class EaterThread extends Thread {
    private final Random random;
    private final Table table;

    public EaterThread(String name,Table table,long seed) {
        super(name);
        this.table = table;
        this.random = new Random(seed);
    }

    @Override
    public void run() {
        while(true){
            try {
                String cake = table.take();
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
public class Main {
    public static void main(String[] args) {
        Table table = new Table(3);
        new MakerThread("MakerThread-1",table,31415).start();
        new MakerThread("MakerThread-2",table,92653).start();
        new MakerThread("MakerThread-3",table,58979).start();
        new EaterThread("EaterThread-1",table,32384).start();
        new EaterThread("EaterThread-2",table,62643).start();
        new EaterThread("EaterThread-3",table,38327).start();
    }
}

 

 

 

 

三、模式讲解

Producer-Consumer模式的角色如下:

  • Data(数据)

Data代表了实际生产和消费的数据。

  • Producer(生产者)

Producer会创建Data,然后传递给Channel。

  • Consumer(消费者)

Consumer从Channel获取Data数据,进行处理。

  • Channel(通道)

Channel从Producer处接受Data,并保管起来,并应Consumer的要求,将Data传送出去。为确保安全性,Producer与Consumer要对访问共享互斥。

 

 

 

借鉴学习自https://segmentfault.com/a/1190000015558655

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java设计模式是一组经过实践验证的面向对象设计原则和模式,可以帮助开发人员解决常见的软件设计问题。下面是常见的23种设计模式: 1. 创建型模式(Creational Patterns): - 工厂方法模式(Factory Method Pattern) - 抽象工厂模式(Abstract Factory Pattern) - 单例模式(Singleton Pattern) - 原型模式Prototype Pattern) - 建造者模式(Builder Pattern) 2. 结构型模式(Structural Patterns): - 适配器模式(Adapter Pattern) - 桥接模式(Bridge Pattern) - 组合模式(Composite Pattern) - 装饰器模式(Decorator Pattern) - 外观模式(Facade Pattern) - 享元模式(Flyweight Pattern) - 代理模式Proxy Pattern) 3. 行为型模式(Behavioral Patterns): - 责任链模式(Chain of Responsibility Pattern) - 命令模式(Command Pattern) - 解释器模式(Interpreter Pattern) - 迭代器模式(Iterator Pattern) - 中介者模式(Mediator Pattern) - 备忘录模式(Memento Pattern) - 观察者模式(Observer Pattern) - 状态模式(State Pattern) - 策略模式(Strategy Pattern) - 模板方法模式(Template Method Pattern) - 访问者模式(Visitor Pattern) 4. 并发型模式(Concurrency Patterns): - 保护性暂停模式(Guarded Suspension Pattern) - 生产者-消费者模式Producer-Consumer Pattern) - 读写锁模式(Read-Write Lock Pattern) - 信号量模式(Semaphore Pattern) - 线程池模式(Thread Pool Pattern) 这些设计模式可以根据问题的特点和需求来选择使用,它们提供了一些可复用的解决方案,有助于开发高质量、可维护且易于扩展的软件系统。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值