生产者消费者模型

#业务背景

在服务器端实现了一套接口测试业务流程,测试用例执行的时候会生成一些数据,在服务器端和客户端还没有常连接的情况下,怎样处理好C/S两端的交互问题,保证测试数据不丢失?<br>

我想到了生产者消费者设计模型,正好可以解决这个问题。<br>

废话不说,直接上代码:<br>

/**
 * 
 */
package main_example;

/**
 * 测试程序
 * @author liwei
 *
 */
public class Startup {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Controller controller = new Controller();
		Producer producer = new Producer(controller);
		Customer customer = new Customer(controller);

		producer.start();
		customer.start();
	}

}


/**
 * 控制中心
 * @author liwei
 *
 */
class Controller {

	private long number = -1;
	private boolean commodityAvailable = false;

	/**
	 * 从控制中心取回一件商品
	 * @param o 这个参数可以考虑传入调用者,从而实现定向的notify,不会唤起无关的线程,提高程序性能
	 * @return 返回一件商品,在这里一个long型的数据
	 */
	public synchronized long getCommodity(Object o) {
		if (o == null) {
			return -1L;
		}

		// 取商品时,如果商品未就绪,就等待
		while (!commodityAvailable) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		this.commodityAvailable = false;
		notifyAll();

		return number;
	}

	/**
	 * 向控制中心存入一件商品
	 * @param o 这个参数可以考虑传入调用者,从而实现定向notify,不会唤起无关线程,提高程序性能
	 * @param number
	 */
	public synchronized void putCommodity(Object o, long number) {

		if (o == null) {
			return;
		}

		// 入商品时,如果商品已就绪,就等待
		while (commodityAvailable) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		this.number = number;
		this.commodityAvailable = true;
		notifyAll();
	}
}

/**
 * 生产者
 * 
 * @author liwei
 *
 */
class Producer extends Thread {

	private Controller controller = null;

	public Producer(Controller controller) {
		this.controller = controller;
	}

	public void run() {
		if (controller == null) {
			return;
		}

		for (int i = 0; i < 10; i++) {
			try {
				Thread.sleep((int) (Math.random() * 3000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			controller.putCommodity(this, i);
			System.out.println("Producer:" + i);
		}
	}
}

/**
 * 消费者
 * 
 * @author liwei
 *
 */
class Customer extends Thread {

	private Controller controller = null;

	public Customer(Controller controller) {
		this.controller = controller;
	}

	@Override
	public void run() {
		if (controller == null) {
			return;
		}

		for (int i = 0; i < 10; i++) {
			try {
				Thread.sleep((int) (Math.random() * 3000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			long count = controller.getCommodity(this);
			System.out.println("Customer:" + count);
		}
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

互联网速递520

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值