- import java.util.Random;
- import java.util.concurrent.Executors;
- public class ServiceWindow {
- private ConsumerType type=ConsumerType.COMMON;
- private int windowID = 1;
-
- public void setType(ConsumerType type) {
- this.type = type;
- }
- public void setWindowID(int windowID) {
- this.windowID = windowID;
- }
-
- //启动服务
- public void start(){
- Executors.newSingleThreadExecutor().execute(new Runnable(){
- public void run() {
- String windowName = windowID+"号"+type+"窗口";
- while(true){
- service(ServiceWindow.this.type,windowName);
- }
- }
- });
- }
-
- //窗口服务
- public void service(ConsumerType type,String windowName) {
- Integer number = getServiceNumber(type);
- System.out.println(windowName+"正在获取"+type+"客户号码");
- if(number!=null){
- System.out.println(windowName+"正在为"+number+"号"+type+"客户服务");
- long startTime = System.currentTimeMillis();
- int serviceTime = getServiceTime(type);
- sleep(serviceTime);
- long endTime =System.currentTimeMillis();
- long costTime = (endTime - startTime)/1000;
- System.out.println(windowName+"为"+"第"+number+"号"+type+"客户完成服务,耗时"+costTime+"秒");
- }
- else{
- //如果是普通用户窗口,那么就休息
- if(type.equals(ConsumerType.COMMON)){
- System.out.println(windowName+"没有取到号,休息一秒钟");
- sleep(1000);
- }else{
- //如果是非普通用户窗口,就开始为普通用户服务,使用递归调用
- System.out.println(windowName+"没有取到号,"+"开始为普通客户服务");
- service(ConsumerType.COMMON,windowName);
- }
- }
- }
- //获得服务号码
- public Integer getServiceNumber(ConsumerType type) {
- Integer number =null;
- switch(type){
- case COMMON:
- number = NumberMachine.getInstance().getCommonManager().fetchNumber();
- break;
- case EXPRESS:
- number = NumberMachine.getInstance().getExpressManager().fetchNumber();
- break;
- case VIP:
- number = NumberMachine.getInstance().getVipManager().fetchNumber();
- break;
- }
- return number;
- }
- //获取服务时间
- public int getServiceTime(ConsumerType type) {
- int serviceTime=0;
- switch(type){
- case COMMON:
- case VIP:
- int randomTime =Constant.MAX_SERVICE_TIME-Constant.MIN_SERVICE_TIME;
- serviceTime = new Random().nextInt(randomTime+1)+Constant.MIN_SERVICE_TIME;
- break;
- case EXPRESS:
- serviceTime =Constant.MIN_SERVICE_TIME;
- break;
-
- }
- return serviceTime;
-
- }
- //获得停滞时间
- public void sleep(int sleepTime) {
- try {
- Thread.sleep(sleepTime);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
复制代码 张老师视频说,可以用继承来做,但我在做的时候,发现继承更麻烦(主要是vip,快速又要调用普通这块),索性进行了抽取优化,欢迎拍砖。如果有谁用继承进行了优化,希望能把代码也贴出来,互相交流~ |
|