设计模式之生成者与消费者模式

1、生产者与消费者模式

多线程中,生成者与消费者是一个很典型的例子。生产者就是生产数据的线程,消费者就是消费数据的线程。生产者与消费者模式是通过一个共享资源缓冲区来解决生产者和消费者的强耦合问题,生产者与消费者之间不需要通信,生产者生产的产品放入阻塞队列中,而消费者从阻塞队列中从取出产品,阻塞队列就相当于一个缓冲区, 同时生成与消费还需要有一个生产与消费的平衡,这样讲生成者与消费者进行解耦。

2、代码实现

下面用生产汽车的简单例子说明:

/**
 * 生成的汽车产品
 *
 */
public class Car {

	private int id;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
	
	@Override
	public String toString() {
		return "汽车编号为:"+id;
	}
	
}
/**
 * 仓库对象,生产者生产的产品放在仓库中,供消费者从仓库中取产品
 *
 */
public class DepotStack {
	private final int MAXSIZE = 10;
	
	BlockingQueue<Car> queues = new LinkedBlockingQueue<Car>(10);
	
	
	//存产品
	public void push(Car c){
	//	System.out.println("--------"+Thread.currentThread().getName()+"抢到资源");
		if(queues.size()<MAXSIZE){
			try {
				queues.put(c);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"向仓库放入车"+c.getId());
		}else{
			System.out.println("仓库已存储满");
			try {
				Thread.currentThread().sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	
	//取产品
	public Car pop(){
		Car c = null;
	//	System.out.println("*********"+Thread.currentThread().getName()+"抢到资源");
		if(queues.size()==0){
			try {
				System.out.println("仓库为空");
				Thread.currentThread().sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
		try {
			c = queues.take();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+"从仓库取出车"+c.getId());	
		return c;
	}
	
	
}
public class Producer extends Thread{

	private DepotStack depotStack;
	
	public Producer(DepotStack depotStack) {
		this.depotStack = depotStack;
	}

	@Override
	public void run() {
		while(true){
			for (int i=0;i<10;i++) {
				Car car = new Car();
				car.setId(i);
				depotStack.push(car);
			}
		}
	}
	
}
/**
 * 消费者
 *
 */
public class Customer extends Thread{

	private DepotStack depotStack;
	
	public Customer(DepotStack depotStack) {
		super();
		this.depotStack = depotStack;
	}


	@Override
	public void run() {
		while (true) {
			depotStack.pop();
		}
	}
	
	
}
	public static void main(String[] args) {
		
		DepotStack depotStack = new DepotStack();
		Producer producer = new Producer(depotStack);
		producer.setName("生成者1");
		Customer customer = new Customer(depotStack);
		customer.setName("消费者1");
		
		producer.start();
		customer.start();
		
	}
测试结果:















  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值