生产者消费者模式实现

生产者与消费者解耦,典型应用:MQ。不多解释,code talking:


调用模块:

package com.array7.ds.pc;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

public class Run {
	public static void main(String[] args) {
		BlockingDeque<Integer> queue = new LinkedBlockingDeque<Integer>(50);
		int stopConditon = 100;
		new Productor(queue).begin(stopConditon);
		new Customer(queue).begin(stopConditon);
		
	}
}


生产者模块:


package com.array7.ds.pc;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.atomic.AtomicInteger;

public class Productor {
	static AtomicInteger flag = new AtomicInteger(0);
	private BlockingDeque<Integer> queue;

	public Productor(BlockingDeque<Integer> queue) {
		this.queue = queue;
	}

	public void begin(int stopConditon) {
		new Thread(new Create(queue, stopConditon)).start();
	}

	public static class Create implements Runnable {
		private BlockingDeque<Integer> queue;
		private int stopConditon;

		public Create(BlockingDeque<Integer> queue, int stopConditon) {
			this.queue = queue;
			this.stopConditon = stopConditon;
		}

		@Override
		public void run() {
			while (true) {
				try {
					Thread.sleep(5);
					int i = flag.incrementAndGet();
					if (i == stopConditon) {
						queue.put(i);
						System.out.println("stop put element >>> ");
						break;
					}
					queue.put(i);
					System.out.println("put element >>> " + i);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}
}

消费者模块

package com.array7.ds.pc;

import java.util.concurrent.BlockingDeque;

public class Customer {
	BlockingDeque<Integer> queue;

	public Customer(BlockingDeque<Integer> queue) {
		this.queue = queue;
	}

	public void begin(int stopConditon) {
		new Thread(new Get(queue, stopConditon)).start();
	}

	public static class Get implements Runnable {
		private BlockingDeque<Integer> queue;
		private int stopConditon;

		public Get(BlockingDeque<Integer> queue, int stopConditon) {
			this.queue = queue;
			this.stopConditon = stopConditon;
		}

		@Override
		public void run() {
			while (true) {
				try {

					Thread.sleep(10);
					Integer e = queue.take();
					if (e != null) {
						if (e.intValue() == stopConditon) {
							System.out.println("stop get element >>>>>> ");
							break;
						}
						System.out.println("get element >>>>>> " + e);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值