生产者-消费者模式(异步、线程间)

生产者-消费者模式(异步、线程间)

package com.lx.day0428;

import java.util.LinkedList;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Test {

	public static void main(String[] args) {
		// 消息队列
		MessageQueue messageQueue = new MessageQueue(2);
		
		for (int i = 0; i < 3; i++) {
			// lamdba 表达式禁止修改外部变量
			int id = i;
			new Thread(() -> {
				messageQueue.put(new Message(id, "值" + id));
			}, "生产者" + id).start();
		}
		
		new Thread(() -> {
			while (true) {
				try {
					Thread.sleep(1000);
					Message message = messageQueue.take();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, "消费者").start();
	}
	
}

/**
 * 消息队列类
 */
@Slf4j
class MessageQueue {
	
	/**
	 * 消息队列集合
	 */
	private LinkedList<Message> list = new LinkedList<Message>(); 
	
	/**
	 * 队列容量
	 */
	private int capcity;
	
	/**
	 * @param capcity 队列容量
	 */
	public MessageQueue(int capcity) {
		this.capcity = capcity;
	}

	/**
	 * 获取消息
	 */
	public Message take() {
		// 检查消息队列是否为空
		synchronized (list) {
			while (list.isEmpty()) {
				try {
					log.info("队列为空,消费者线程等待");
					list.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			// 从队列的头部获取消息返回
			Message message = list.removeFirst();
			log.info("已消费一个消息:{}", message);
			list.notifyAll();
			return message;
		}
	}
	
	/**
	 * 存入消息
	 */
	public void put(Message message) {
		synchronized (list) {
			// 检查队列是否已满
			while (list.size() == capcity) {
				try {
					log.info("队列已满,生产者线程等待");
					list.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			// 将消息加入队列的尾部
			list.addLast(message);
			log.info("已生产一个消息:{}", message);
			list.notifyAll();
		}
	}
	
}

/**
 * 消息类
 */
final class Message {
	/**
	 * 唯一标识
	 */
	private int id;
	
	/**
	 * 消息内容
	 */
	private Object value;
	
	/**
	 * @param id 唯一标识
	 * @param value 消息内容
	 */
	public Message(int id, Object value) {
		this.id = id;
		this.value = value;
	}

	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	@Override
	public String toString() {
		return "Message [id=" + id + ", value=" + value + "]";
	}
	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值