实现生产者-消费者模式的五种方式

在学习完 RabbitMQ 后,才明白为什么那么喜欢问生产者-消费者问题,因为在很多开发领域都能派上用场。
Java基础 以及 操作系统 都有接触,但还是要在这里再总结一下。


实现方式

生产者消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一存储空间,生产者向空间里生产数据,而消费者取走数据。

保证同一时刻只有一个线程读或写:

  • 用synchronized对存储加锁,然后用object原生的wait() 和 notify()做同步
  • 用concurrent.locks.Lock,然后用condition的await() 和signal()做同步
  • 使用信号量semaphore

保证存储内部的读写唯一

  • 直接使用concurrent.BlockingQueue
  • 使用PipedInputStream/PipedOutputStream

synchronized、wait()、notify()

  • wait():当缓冲区已满/空时,生产者/消费者线程停止自己的执行,放弃锁,使自己处于等待状态,让其他线程执行。
  • notify():当生产者/消费者向缓冲区放入/取出一个产品时,向其他等待的线程发出可执行的通知,同时放弃锁,使自己处于等待状态。

实现

		public class Main {
   
			static int i = 0;
			static int size = 10;
			Queue<String> queue = new LinkedList<String>();
			
			public static void main(String[] args) {
   
				Main main = new Main();
				main.new Producter("producter[1]").start();
				main.new Producter("producter[2]").start();
				main.new Consumer("consumer[1]").start();
				main.new Consumer("consumer[2]").start();
				main.new Consumer("consumer[3]").start();
		
			}
			
			//生产者
			class Producter extends Thread{
   
				private String name;
				
				public Producter(String name) {
   
					this.name = name;
				}
		
				@Override
				public void run() {
   
					while(true){
   
						synchronized (queue) {
   
							while(queue.size()==size){
   
								System.out.println("The queue is full! "+name+" is waiting for Consumer");
								try {
   
									queue.wait();
								} catch (InterruptedException e) {
   
									e.printStackTrace();
								}
							}
							System.out.println(name+":product====>production_"+i);
							queue.offer("production_" + i);
							i++;
							queue.notifyAll();
						}
						try {
   
							sleep(new Random().nextInt(1000));
						} catch (InterruptedException e) {
   
							e.printStackTrace();
						}
					}
				}
			}
			
			//消费者
			class Consumer extends Thread{
   
				private String name;
					
				public Consumer(String name) {
   
					this.name = name;
				}
					
				@Override
				public void run() {
   
					while(true){
   
						synchronized (queue) {
   
							while(queue.isEmpty()){
   
								System.out.println("The queue is empty! "+name+" is waiting for Producter");
								try {
   
									queue.wait();
								} catch (InterruptedException e) {
   
									e.printStackTrace();
								}
							}
							String s = queue.poll();
							System.out.println(name+":consume====>"+s);
							queue.notifyAll();
						}
						try {
   
							sleep(new Random().
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值