java 生产者消费者模式

  java的生产者消费者模式,有三个部分组成,一个是生产者,一个是消费者,一个是缓存。

这么做有什么好处呢?
1.解耦(去依赖),如果是消费者直接调用生产者,那如果生产者的代码变动了,消费者的代码也需要随之变动
2.高效,如果消费者直接掉生产者,执行时间较长的话,会阻塞,影响其他业务的进行
3.负载均衡,如果消费者直接调生产者,那生产者和消费者就得在一起了,日后业务量非常大的话,要想减轻服务器的压力,想拆分生产和消费,就很困难

/**
 * 我是生产者,负责生产
 */
public class Product implements Runnable {
	private Queue q;

	public Product(Queue q) {
		this.q = q;
	}

	@Override
	public void run() {
		try {
			for (int i = 0; i < 3; i++) {
				q.product("test" + i);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}


/**
 *我是消费者,负责消费
 */
public class Consumer implements Runnable {
	private Queue q;
	
	public Consumer(Queue q){
		this.q = q;
	}
	
	@Override
	public void run() {
		try {
			for(int i=0 ; i < 3 ; i++){
				q.consumer();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

/**
 * 
 *我是缓存,负责产品的存(生产后的放置)取(消费时的获取)
 */
public class Queue {
	private final Object lock = new Object();
	private List<String> list = new ArrayList<String>();

	public void product(String param) throws InterruptedException {
		synchronized (lock) {
			System.out.println("product生产");
			list.add(param);
			lock.notify();
			lock.wait();
		}
	}

	public void consumer() throws InterruptedException {
		synchronized (lock) {
			lock.wait();

			System.out.println("product消费");
			if (list.size() > 0) {
				list.remove(list.size() - 1);
			}
			lock.notify();
		}
	}

}

public class TestMain {
	public static void main(String[] args) {
		Queue q = new Queue();
		Product p = new Product(q);
		Consumer s = new Consumer(q);
		
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(s);
		
		t1.start();
		t2.start();
	}
}

posted @ 2017-04-27 15:27  Bug开发攻城狮  阅读(171)  评论(0编辑  收藏  举报