#业务背景
在服务器端实现了一套接口测试业务流程,测试用例执行的时候会生成一些数据,在服务器端和客户端还没有常连接的情况下,怎样处理好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);
}
}
}