import java.util.concurrent.TimeUnit;
public class ServantThread extends Thread{
//服务顾客数目
private static int customerNum = 0;
//总等待时间
private static int sumWaitTime = 0;
//总服务时间
private static int sumServeTime = 0;
//最大等待时间
private static int maxWaitTime = 0;
private boolean flag = false;
//服务台名
private String name;
public ServantThread(String name) {
super(name);
this.name = name;
}
public static int getMaxWaitTime() {
return maxWaitTime;
}
public static int getSumServeTime() {
return sumServeTime;
}
@Override
public void run() {
flag = true;
while (flag) {
CustomerBean customer = CustomerQuene.getCustomerQuene().getCustomerBean();
//如果顾客线程已经关闭且队列中没有顾客,服务台线程关闭释放
if (customer == null) {
if (!CustomerQuene.getCustomerQuene().isFlag()) {
flag = false;
print();
}
continue;
}
long now = System.currentTimeMillis();
//保存最大的等待时间
int waitTime = (int) (now - customer.getArriveTime());
if (waitTime > maxWaitTime) {
maxWaitTime = waitTime;
}
//睡眠时间为顾客的服务时间,代表这段时间在服务顾客
try {
TimeUnit.MILLISECONDS.sleep(customer.getServeTime());
} catch (Exception e) {
e.printStackTrace();
}
System.err.println(name + " 服务顾客耗时:" + customer.getServeTime() + "ms\t顾客等待:" + waitTime + "ms");
customerNum++;
sumWaitTime += waitTime;
sumServeTime += customer.getServeTime();
}
}
public static void print() {
if (customerNum > 0) {
System.out.println("--------------------------------------");
System.out.println("服务顾客数目:" + customerNum);
System.out.println("最大等待时间:" + maxWaitTime+"ms");
System.out.println("最大等待顾客数目:" + CustomerQuene.getCustomerQuene().getMaxWaitNum());
//输出顾客平均等待时间,保留两位小数
System.out.println("顾客平均等待时间:" + ((sumWaitTime * 1.0 / customerNum)) + "ms");
System.out.println("顾客平均服务时间:" + ((sumServeTime * 1.0 / customerNum)) + "ms");
System.out.println("系统总服务时间:" + sumServeTime + "ms");
}
}
}
评论0