生产者消费者模式

生产者消费者模式

首先实现一个EventQueue,用来缓存待处理事件,代码如下:

package com.yozzs.PAndC;

import java.util.LinkedList;

import static java.lang.Thread.currentThread;

public class EventQueue {
    //最大可缓存事件数
    private final int max;
    //待处理事件
    static class Event{}
    //队列
    private static LinkedList<Event> eventQueue = new LinkedList<>();
    //默认最大值
    private static final int DEFUALT_MAX_EVENT = 10;

    public EventQueue(int max) {
        this.max=max;
    }

    public EventQueue() {
        this(DEFUALT_MAX_EVENT);
    }

    //加入事件到队列
    public void produce(Event event){
        synchronized (eventQueue){
            while(eventQueue.size()>=max){
                console("队列已满!");
                try {
                    eventQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            eventQueue.addLast(event);
            console("事件已添加!");
            eventQueue.notifyAll();
        }
    }

    //处理事件(从队列中移除事件)
    public Event consume(){
        synchronized (eventQueue){
            while(eventQueue.size()<=0){
                console("队列为空!");
                try {
                    eventQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Event event = eventQueue.removeFirst();
            console("事件已处理!");
            eventQueue.notifyAll();
            return event;
        }
    }

    private void console(String message) {
        System.out.printf("%s:%s\n",currentThread().getName(),message);
    }

}

测试代码:

package com.yozzs.PAndC;

import java.util.concurrent.TimeUnit;

public class EventClient {
    public static void main(String[] args) {
        final EventQueue eventQueue = new EventQueue();

        for (int i = 1; i <= 5; i++) {
            new Thread(() -> {
                while (true) {
                    eventQueue.produce(new EventQueue.Event());
                }
            }, "Producer" + i).start();
            new Thread(() -> {
                while (true) {
                    eventQueue.consume();
                    try {
                        TimeUnit.SECONDS.sleep(10);//模拟处理事件耗时10秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "Consumer" + i).start();
        }
    }
}

这里启动5个生产者线程和5个消费者线程,执行结果如下:
这里写图片描述


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值