生产者与消费者模式,是一道非常经典的设计模式,所涉及到的是多线程协调工作的问题。在Java中,一般是通过wait()和notify()方法进行解决。
下面附上关于这种设计模式的源码:
- //仓库类
- public class Store {
- private final int MAX_SIZE;//仓库的最大容量
- private int count;//当前的货物数量
- public Store(int n){//初始化最大容量的构造方法
- MAX_SIZE = n;
- count = 0;
- }
- //往仓库加货物的方法
- public synchronized void add(){
- while(count >= MAX_SIZE){//每次执行都判断仓库是否已满
- System.out.println("已经满了");
- try {
- this.wait();//如果满了,就进入等待池
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- count++;//数量加1
- //打印当前仓库的货物数量
- System.out.println(Thread.currentThread().toString()+"put"+count);
- //仓库中已经有东西可以取了,则通知所有的消费者线程来拿
- this.notifyAll();
- }
- //从仓库拿走货物的方法
- public synchronized void remove(){
- while(count<=0){
- System.out.println("空了");//每次执行都判断仓库是否为空
- try {
- this.wait();//如果为空,就进入等待池
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- //打印当前仓库的货物数量
- System.out.println(Thread.currentThread().toString()+"get"+count);
- count--;//数量减1
- //仓库还没装满,通知生产者添加货物
- this.notifyAll();
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- Store s = new Store(5);
- //创建两个生产者和两个消费者
- Thread pro1 = new Producer(s);
- Thread con1 = new Consumer(s);
- Thread pro2 = new Producer(s);
- Thread con2 = new Consumer(s);
- pro1.setName("producer1");
- con1.setName("consumer1");
- pro2.setName("producer2");
- con2.setName("consumer2");
- //启动线程
- pro1.start();
- con1.start();
- pro2.start();
- con2.start();
- }
- }
- class Producer extends Thread{//生产者线程类
- private Store s;
- public Producer(Store s){
- this.s = s;
- }
- public void run(){//线程方法
- while(true){//循环
- s.add();//往仓库加货物
- try {
- Thread.sleep(1000);//设置线程休息1s
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- class Consumer extends Thread{//消费者线程类
- private Store s;
- public Consumer(Store s){
- this.s = s;
- }
- public void run(){//线程方法
- while(true){//循环
- s.remove();//从仓库取走货物
- try {
- Thread.sleep(1500);//设置线程休息1.5s
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
运行结果如下:
- ……
- Thread[producer1,5,main]put5
- Thread[consumer2,5,main]get5
- Thread[consumer1,5,main]get4
- Thread[producer2,5,main]put4
- Thread[producer1,5,main]put5
- 已经满了
- Thread[consumer2,5,main]get5
- Thread[producer2,5,main]put5
- Thread[consumer1,5,main]get5
- Thread[producer1,5,main]put5
- 已经满了
- Thread[consumer1,5,main]get5
- ……
其中,我们可以通过调节两个线程类的
- Thread.sleep(1000);
来控制生产者与消费者的关系。