场景设计:用OOP的思想设计一个生产者消费者的模型

具体模型如下:

  • 有若干个消费者,每个消费者都可以独立的执行消费任务,偶尔会因为某种原因,该消费者会不可用,这个时候不能在给他分配消费任务了。
  • 此外还有大量待消费的生产品,每个消费者都可以一个耗时的IO操作。
  • 设计一个对象模型来满足这个场景。

说一些思路,这个问题首先可以使用阻塞队列来直接构建,因为本身就可以直接应用其生产者消费者模型来进行。然后就是一些搭建的思路!
这里将生产者创建一个类,然后再类内创建一个线程专门用来生产!

class Patient{
    BlockingQueue<Integer> queue;
    Thread thread;
    public Patient(BlockingQueue<Integer> queue){
        this.queue = queue;
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                produce();
            }
        });
    }

    public void produce(){
        int i=0;
        while (true){
            try {
                queue.put(i++);
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

然后是消费者这块,也创建一个类,同样类内创建一个线程用来消费产品。并且需要增加一个为了实现要求中“偶尔会因为某种原因,该消费者会不可用”的方法。以及恢复其功能的方法。这里我使用加锁的方式来实现。

class Nurse{
    ReentrantLock lock = new ReentrantLock();
    BlockingQueue<Integer> queue;
    Thread thread;
    String str;

    public Nurse(BlockingQueue<Integer> queue,String str){
        this.str = str;
        this.queue = queue;
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!queue.isEmpty()){
                    try {
                        lock.lock();
                        Integer integer = queue.take();
                        System.out.println(str+"正在处理"+integer);
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }
            }
        });
    }

    //停止护士的工作
    public void stop(){
        lock.lock();
        System.out.println(this.str+"停止工作");
    }

    public void reset(){
        lock.unlock();
        System.out.println(this.str+"重新工作");
    }
}

最终则在主函数中,只需要创建生产者和相应的消费者即可。

public class application_BlockingQueue {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(20);

        Patient patient = new Patient(queue);


        Nurse n1 = new Nurse(queue,"nurse1");
        Nurse n2 = new Nurse(queue,"nurse2");

        patient.thread.start();
        n1.thread.start();
        n2.thread.start();

        Thread.sleep(300);
        n1.stop();
        Thread.sleep(1500);
        n1.reset();

    }
}

最终效果如下:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值