Statements: This blog was written by me, but most of content  is quoted from book【Data Structure with Java Hubbard】

【Description】

This simulationillustrates objectoriented programming(OOP). Java objects are instantiated to represent all the interacting

clients and servers.To that end, we first define Clientand Serverclasses.This is an event driven simulation,

where clients arrive for service at random times and services have random durations.

Each client will have an arrival time, a time when service starts, and a time when it ends. All time values will be integers.

//  Data Structures with Java, Second Edition
// by John R. Hubbard
// Copyright 2007 by McGraw-Hill package com.albertshao.ds.simation; public class Client {
private int id;
private int startTime; public Client(int id, int time) {
this.id = id;
System.out.printf("%s arrived at time %d.%n", this, time);
} public void setStartTime(int time) {
startTime = time;
} public String toString() {
return "#" + id;
}
}

EachServerobject also stores the time when it will stop serving its current client.That time is

computed by adding its service time (a positive random integer) to the time when it begins serving that

client. The random number generator used togenerate those service times is stored as a randomfield in

the Serverobject. A server’s actual servicetime varies with each client. But the server’s average service

time is a fixed property of the server, initialized when the Serverobject is constructed (at line 10):

//  Data Structures with Java, Second Edition
// by John R. Hubbard
// Copyright 2007 by McGraw-Hill package com.albertshao.ds.simation; public class Server {
private Client client;
private int id;
private int stopTime = -1;
private double meanServiceTime;
private ExpRandom random; public Server(int id, double meanServiceTime) {
this.id = id;
this.meanServiceTime = meanServiceTime;
this.random = new ExpRandom(meanServiceTime);
} public double getMeanServiceTime() {
return meanServiceTime;
} public int getStopTime() {
return stopTime;
} public boolean isIdle() {
return client == null;
} public void startServing(Client client, int time) {
this.client = client;
this.client.setStartTime(time);
this.stopTime = time + random.nextInt();
System.out.printf("%s started serving client %s at time %d, stop time %d.%n",
this, client, time, this.stopTime);
} public void stopServing(int time) {
System.out.printf("%s stopped serving client %s at time %d.%n",
this, client, time);
client = null;
} public String toString() {
return "Server " + "ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(id);
}
}

For a simulation to be realistic, it must use randomly generated numbers to simulate the natural uncertainty of the real word. Those random numbers should have the same distribution as the natural uncertainties that they represent. Service times and time between client arrivals both tend to be distributed exponentially. That means that the probability that the time tis less than a number xis p= 1 – e-Ox. But the Math.random()method returns numbers that are uniformly distributed in the range 0 dp< 1. So to convert the random number pto the exponentially distributed random variable x, we solve the equation, obtaining x= –(1/O)ln(1 –p). The constant 1/Ois the mean of the distribution. Thus we code the nextDouble()method as shown at line 9:

//  Data Structures with Java, Second Edition
// by John R. Hubbard
// Copyright 2007 by McGraw-Hill package com.albertshao.ds.simation; public class ExpRandom {
private double mean; public ExpRandom(double mean) {
this.mean = mean;
} public double nextDouble() {
return -mean*Math.log(1 - Math.random());
} public int nextInt() {
return (int)Math.ceil(nextDouble());
}
}

The actual simulation is performed by the main class shown below. Itsets four constants for the simulation at lines 2–5: the number of servers, the number of clients arrivingfor service, the mean service time among the servers, and the mean timebetween arrivals for the clients.

//  Data Structures with Java, Second Edition
// by John R. Hubbard
// Copyright 2007 by McGraw-Hill package com.albertshao.ds.simation;
import java.util.*; public class Simulation {
private static final int SERVERS = 3;
private static final int CLIENTS = 12;
private static final int MEAN_SERVICE_TIME = 25;
private static final int MEAN_ARRIVAL_TIME = 4;
private static Queue<Client> queue = new ArrayDeque<Client>();
private static ExpRandom randomService = new ExpRandom(MEAN_SERVICE_TIME);
private static ExpRandom randomArrival = new ExpRandom(MEAN_ARRIVAL_TIME);
private static Server[] servers = new Server[SERVERS];
private static Client[] clients = new Client[CLIENTS]; public Simulation() {
String fmt = "%-27s %6d%n";
System.out.printf(fmt, "Number of servers:", SERVERS);
System.out.printf(fmt, "Number of clients:", CLIENTS);
System.out.printf(fmt, "Mean service time:", MEAN_SERVICE_TIME);
System.out.printf(fmt, "Mean interarrival time:", MEAN_ARRIVAL_TIME);
for (int i=0; i<SERVERS; i++) {
double meanServiceTime = randomService.nextDouble();
servers[i] = new Server(i, meanServiceTime);
System.out.printf("Mean service time for %s: %4.1f%n",
servers[i], servers[i].getMeanServiceTime());
}
int nextArrivalTime = 0;
for (int t=0, clientId=0; clientId < CLIENTS; t++) {
if (t == nextArrivalTime) {
nextArrivalTime = t + randomArrival.nextInt();
Client client = clients[clientId] = new Client(++clientId, t);
queue.add(client);
System.out.println("\tClient queue: " + queue);
}
for (Server server : servers) {
if (t == server.getStopTime()) {
server.stopServing(t);
}
if (server.isIdle() && !queue.isEmpty()) {
Client client = (Client)queue.remove();
System.out.println("\tClient queue: " + queue);
server.startServing(client,t);
}
}
}
} public static void main(String[] args) {
new Simulation();
}
}

The result is :

Number of servers:               3
Number of clients: 12
Mean service time: 25
Mean interarrival time: 4
Mean service time for Server A: 15.3
Mean service time for Server B: 5.3
Mean service time for Server C: 63.0
#1 arrived at time 0.
Client queue: [#1]
Client queue: []
Server A started serving client #1 at time 0, stop time 31.
Server A stopped serving client #1 at time 31.
#2 arrived at time 33.
Client queue: [#2]
Client queue: []
Server A started serving client #2 at time 33, stop time 61.
#3 arrived at time 38.
Client queue: [#3]
Client queue: []
Server B started serving client #3 at time 38, stop time 64.
#4 arrived at time 42.
Client queue: [#4]
Client queue: []
Server C started serving client #4 at time 42, stop time 91.
#5 arrived at time 43.
Client queue: [#5]
#6 arrived at time 44.
Client queue: [#5, #6]
#7 arrived at time 45.
Client queue: [#5, #6, #7]
#8 arrived at time 52.
Client queue: [#5, #6, #7, #8]
#9 arrived at time 53.
Client queue: [#5, #6, #7, #8, #9]
#10 arrived at time 59.
Client queue: [#5, #6, #7, #8, #9, #10]
#11 arrived at time 61.
Client queue: [#5, #6, #7, #8, #9, #10, #11]
Server A stopped serving client #2 at time 61.
Client queue: [#6, #7, #8, #9, #10, #11]
Server A started serving client #5 at time 61, stop time 80.
Server B stopped serving client #3 at time 64.
Client queue: [#7, #8, #9, #10, #11]
Server B started serving client #6 at time 64, stop time 65.
Server B stopped serving client #6 at time 65.
Client queue: [#8, #9, #10, #11]
Server B started serving client #7 at time 65, stop time 70.
#12 arrived at time 70.
Client queue: [#8, #9, #10, #11, #12]
Server B stopped serving client #7 at time 70.
Client queue: [#9, #10, #11, #12]
Server B started serving client #8 at time 70, stop time 71.

【DataStructure】One of queue usage: Simulation System的更多相关文章

  1. 【DataStructure】Description and usage of queue

    [Description] A queue is a collection that implements the first-in-first-out protocal. This means th ...

  2. 【DataStructure】Description and Introduction of Tree

    [Description] At ree is a nonlinear data structure that models a hierarchical organization. The char ...

  3. 【翻译】Sencha Touch2.4 The Layout System 布局

    [翻译]The Layout System 布局 In Sencha Touch there are two basic building blocks: componentsand containe ...

  4. 【DataStructure】Charming usage of Set in the java

    In an attempt to remove duplicate elements from list, I go to the lengths to take advantage of  meth ...

  5. 【高精度递推】【HDU1297】Children’s Queue

    Children's Queue Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...

  6. 【DataStructure】The description of Java Collections Framework

    The Java Connections FrameWork is a group of class or method and interfacs in the java.util package. ...

  7. 【LeetCode】232. Implement Queue using Stacks

    题目: Implement the following operations of a queue using stacks. push(x) -- Push element x to the bac ...

  8. 【c#】队列(Queue)和MSMQ(消息队列)的基础使用

    首先我们知道队列是先进先出的机制,所以在处理并发是个不错的选择.然后就写两个队列的简单应用. Queue 命名空间 命名空间:System.Collections,不在这里做过多的理论解释,这个东西非 ...

  9. 【转】C++ Incorrect Memory Usage and Corrupted Memory(模拟C++程序内存使用崩溃问题)

    http://www.bogotobogo.com/cplusplus/CppCrashDebuggingMemoryLeak.php Incorrect Memory Usage and Corru ...

随机推荐

  1. guice整合struts2,guice的使用(八)

    平时我们习惯用了spring整合struts2,今天我们就来见识一下guice整合struts2吧. 看web.xml配置: <?xml version="1.0" enco ...

  2. Solr.NET快速入门(二)

    字典映射和动态字段 Solr dynamicFields可以根据用例不同地映射. 它们可以被"静态地"映射,例如,给定: <dynamicField name="p ...

  3. 兼容各个浏览器的jquyer zclip复制文本插件 无效的解决办法

    项目中使用点击文本复制功能,用了这个兼容各个浏览器的插件,但是发现放在最前面正常,放到嵌套的html中就失效. 解决办法: <span style="position: relativ ...

  4. js判断浏览器是android还是ios还是微信浏览器

    第一种方法<script type="text/javascript"> //判断访问终端 var browser={ versions:function(){ var ...

  5. vue首次进入微信没有标题问题

    首先实在路由改变的时候可以有标题的    首次进入路由不显示标题,查到很多,最有解决可以自定义标签, 后者引入一个包vue-wechat-title,我就是用的后者,前面的没有式过 上地址  http ...

  6. js 或运算

    表达式a && 表达式b : 计算表达式a(也可以是函数)的运算结果, 如果为 True, 执行表达式b(或函数),并返回b的结果: 如果为 False,返回a的结果: 表达式a || ...

  7. python学习小结

    1学习的课程名字叫什么 python:前端初识html,后台基础flask 2怎么输出一句话,用代码举例 输出用:print 例如: 3使用终端工具怎么运行 Python代码 例如我要运行题目2的程序 ...

  8. C# html代码生成word

    首先引入 Microsoft.Office.Interop.Word 其次要先说一下,把一大段html代码直接变成word文件,只能生成doc文件,docx文件应该是不行的 首先我们用IO生成一个do ...

  9. 找到多个与名为“HOME”的控制器匹配的类型。如果为此请求(“{CONTROLLER}/{ACTION}/{ID}”)提供服务的路由在搜索匹配此请求的控制器时没有指定命名空间,则会发生此情况。如果是这样,请通过调用含有“NAMESPACES”参数的“MAPROUTE”方法的重载来注册此路由。

    public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/ ...

  10. win10卸载瑞星

    下载了一个软件,没有注意就不小心装上了瑞星这个流氓软件 百度N种办法并不能解决~ 我试过正常卸载.试过WIN自带卸载.试过重装再卸载 最后采取最傻瓜最暴力的办法 ctrl+alt+delete 打开任 ...