02-Queue Modul Using Java - Queue API
02-Queue Modul Using Java - Queue API
Queue 1
Section A
Service Simulation
In this topic, we will learn about queue through some problems by
using service simulation. Service simulation is used to imitate the real
operation system and gather statistic of certain information. Statistical
report that can be generated by simulation are arrival rates and
patterns, waiting and service times and percentage of time the
automated equipment is utilized. Queue in service simulation is the replication of the real queue. Thus, it will
retain the queue concept: first item in queue will be served prior to the next item.
Beside queue concept, other information that you need to identify regarding service simulation is its
complexity. These complexities depend on (1) the number of servers (example: counter) and (2) the number
of services provided.
Since the real situation often involves many customers and services, it would be easier if the simulation process
can be assisted by computer. Such advantages of using computer to do simulation are:
1st : The information would be gathered without involving real customers.
2nd : A simulation by computer can be faster than the actual implementation because
of the speed of the computer.
3rd : The simulation could be easily replicated.
In real service system situation, most of the data for example customer arrival time and type of service
required are different among the customers. Hence, random data are needed in order to carry out simulation.
To get the random value, we can either:
(1) use standard input (keyboard or file feeding) or file stream.
(2) randomly generated value using the rand() function.
Queue 2
provided
provided
For the simulation problem discussed in this topic, we will use rand() function to generate the random value
(refer to section: About rand() function).
Usually simulation program will output a statistical information that involves time-based data for instance
arrival_rates, longest_waiting_time and average waiting_time. To hold and process the time-based data, the
simulation program should use a time data type that comprises of 3 attributes: hours, minutes and seconds.
Since it it is not support by Java standard library, we need to define a new class for handling time (refer to
section: About class clockType).
My Note:
Queue 3
About rand() function
rand is a class defined in java.util.Random;. It is used to generate random number.
For using this class to generate random numbers, we have to first create an instance of this class and then
invoke methods such as nextInt(), nextDouble(), nextLong() etc using that instance.
Rand class can be used to generate random numbers of types integers, float, double, long, boolean.
We can pass arguments to the methods for placing an upper bound on the range of the numbers to be
generated.
For example, nextInt(6) will generate numbers in the range 0 to 5 both inclusive.
import java.util.*;
My Note:
Self-study:
1. Write Java statements to obtain a random value from range 1 to 2 using rand function.
2. Write Java statements to obtain and print 10 random value from range 0 to 9 using rand function.
3. Write Java statements to obtain and print 5 random values of below data using random function:
a. Department code from range 1 to 4
b. Subject code from range 0 to 10
The declaration of class Clock comprises of 3 data members of type integer: hr, min and sec, and 11 member
functions with public access: setTime, getTime, printTime, incrementSeconds, incrementMinutes,
incrementHours, equalTime, addTimeMinute, lessThan, earlier, durationSec. This declaration can also be
retrieved from link
http://www.cs.sfu.ca/CourseCentral/101/jregan/SourceCode/Ch8/Clock%20method%20%20toString/Clock.java.
//Default constructor
//Postcondition: hr = 0; min = 0; sec = 0
public Clock()
{
setTime(0, 0, 0);
}
Queue 5
public int getHours()
{
return hr;
}
Queue 6
public void addTimeMinute(int minutes) { //new
for (int i=0; i<minutes; i++)
incrementMinutes();
}
temp.hr = hr;
temp.min = min;
temp.sec = sec;
return temp;
}
Queue 7
str = str + "0" ;
str = str + min + ":";
return str;
}
stop=stopA;
if (stop.sec >= sec) durSec=stop.sec-sec;
else {
durSec=((stop.sec+60) - sec);
borrowMin=true;
}
if (borrowMin)
stop.min-=1;
if (stop.min >= min) durMin=(stop.min-min);
else {
durMin=((stop.min+60) - min);
borrowHour=true;
}
if (borrowHour)
stop.hr-=1;
durHour=(stop.hr - hr);
return (durHour*60)+durMin+(int)(durSec/60.0);
}
The class Clock have been prepared for you to use in your program. We will not discuss the detail of class Clock
in this note, as you already learned about it in OOP topics before this. Please try and play around with the class
Clock.
Queue 8
Clock clock1 = new Clock();
Clock clock2 = new Clock(2,10,40);
Clock washEnd = new Clock();
Once we have declared the respective object of class Clock, we can use it. Below are the examples:
clock1.incrementHours();
clock2.addTimeMinute(10);
clock1.printTime();
washEnd.addTimeMinute(5); // to access the addTimeMinute function for
// object washEnd
int k=i.durationSec(washEnd); // to access the durationSec from object i to washEnd
My Note:
Self-Activity:
Queue 9
About QUEUE
Using Queue Interface from java.util library
The Queue interface is available in java.util package and extends the Collection interface. Being an interface the
queue needs a concrete class for the declaration, in this topic we will use class LinkedList in Java.
Queue 10
About QUEUE
Using Queue Class / Queue API
The class Queue implement the same concept queue as queue in java library. The class Queue is a user defined
class. It holds variables and functions to support the concept of Queue.
The declaration of Queue class comprises of 3 data members, two of them of type Node: first and last and the
int data type with a number of member functions such as enqueuer, dequeuer, peek, size, isEmpty.
The full version of Queue class can also be obtained from UKMFolio.
import java.util.Iterator;
import java.util.NoSuchElementException;
Queue 11
// helper linked list class
private class Node {
private Item item;
private Node next;
}
/**
* Initializes an empty queue.
*/
public Queue() {
first = null;
last = null;
n = 0;
}
Queue 12
}
return s.toString();
}
Tutorial Activity:
Hands-on Activity
1. Mission: Create a program that receives sequence of integers that ends with 0, whenever the integer
is odd push them onto an oddQueue, otherwise push onto evenQueue. Then pop and display the
elements of oddQueue, evenQueue and its size respectively. Display your output in the following
format:
<name of queue> <size of queue>: <elements of the queue>
Sample IO:
Input Output
2 oddQueue 2: 1 5
34 1 8 5 22 0 evenQueue 3: 34 8 22
10 7 16 -2 0 oddQueue 1: 7
evenQueue 3: 10 16 -2
Queue 13
2. Palindrome is a sequence of characters, a word, phrase, number or sequence of words which
reads the same backward as forward. Example of palindrome words are katak, civic and anna.
Write a program that will read the word and identify whether it is a palindrome or not. In this
task, it is compulsory to use Stack and Queue data structure.
Sample I/O:
Input: racecar
Ouput: racecar not a palindrome
Input: p(;(p
Ouput: p(;(p is a Palindrome
Queue 14
Worked-Example 1: ABC Wash Machine
Problem Description
ABC Wash Machine provides a self-wash car for its customer. The customer must queue up in order to get the
service. The customer will immediately be served if the queue is empty. If the machine is free, then it will serve
the front customer in the queue. The machine takes 5 minutes to complete one service. The machine operation
starts at 8.00 am and ends at 8.30 am. However, it will continue serve customer who arrive before or by 8.30
am.
The owner of the ABC Wash Machine would like to know some statistical information so that he can improve
the machine in the future. The information are:
Number of customer that arrives by 8.30 am.
Longest customer waiting time.
Average customer waiting time.
Assume that all customers are an ethical person and determined to get the service, also the machine is ideal.
Input for customer arrival times will randomly generated by rand() function. Assume that the next customer is
likely to arrive within 9 minutes after the current customer.
Your task is to write a program that will print out the above statistical information.
Input
Randomly generated.
Sample Output
Number of customer that arrives by 8.30 am: <Number_ customer _arrives_by 8.30>
Longest customer waiting time: < Longest_waiting_time>
Average customer waiting time: < Average_waiting_time>
Solution
Queue 15
The algorithm for ABC Wash Machine simulation:
Set the operation time.
Generate all car arrivals, and push them onto arrival queue.
Set the initial state for the wash machine (status, startWash, endWash)
Set current event.
While there is still an event
If car arrival event occurs:
Push car onto waiting queue.
If machine finish washing
Update machine state.
If machine available and there is a car waiting:
Front car in waiting queue will be washed.
Remove this car from waiting queue.
Update the machine state and statistical information.
If machine available and there is no car waiting:
Update endWash to beyond operation time.
Jump to the next earliest event that is either car arrival or machine finish washing.
Produce report.
Basic structure
//observation data
Clock totalWaitTime= new Clock();
Clock maxWaitTime = new Clock();
Clock totalServiceTime = new Clock();
Clock startTime= new Clock();
Clock endTime= new Clock();
Clock washEnd = new Clock();
Clock washStart = new Clock();
Clock i;
int nextArrival=0;
Random rand = new Random();
for(i=startTime;(i.lessThan(endTime)||(!waitQueue.isEmpty())||(!arrivalQueue.isEmpty())); )
{
Queue 16
}
1 import java.util.*;
2
3 public class ABCWashMachine {
4 public enum status { free, busy}
5 static int maxDur=0;
6 static int numCar=0;
7 static int totalWait=0;
8 static int totalWork=0;
9
10 public static void main(String[] args) {
11 Clock carArrival;
12 Queue <Clock> waitQueue= new Queue <>();
13 Queue <Clock> arrivalQueue = new Queue<>();
14
15 //enum status {free, busy} machineWash;
16 status machineWash;
17
18 //observation data
19 Clock totalWaitTime= new Clock();
20 Clock maxWaitTime = new Clock();
21 Clock totalServiceTime = new Clock();
22 Clock startTime= new Clock();
23 Clock endTime= new Clock();
24 Clock washEnd = new Clock();
25 Clock washStart = new Clock();
26
27 Clock i;
28 int nextArrival=0;
29 Random rand = new Random();
30
31 startTime.setTime(8,0,0);
32 endTime.setTime(8,30,0); // can change to 12 pm
33
34 for (i=startTime.getCopy();i.lessThan(endTime); ){
35 nextArrival = rand.nextInt(10); nextArrival in the range 0 to 9
36 i.addTimeMinute(nextArrival);
37 if(i.lessThan(endTime)) {
38 arrivalQueue.enqueue(i.getCopy());
39 System.out.println("car arrival: " + i.toString() + " < " +
40 endTime.toString());
41 }
42 }
43
44 //start the simulation
45 machineWash=status.free;
46 if (!arrivalQueue.isEmpty()) {
47 startTime=arrivalQueue.peek();
48 washEnd=startTime.getCopy();
49 washEnd.addTimeMinute(5);
50 } else
51 startTime=endTime.getCopy();
52
Queue 17
53 Clock del;
54 for
55 (i=startTime;(i.lessThan(endTime)||(!waitQueue.isEmpty())||(!arrivalQueue.isEmpty()));)
56 {
57 if (!arrivalQueue.isEmpty())
58 if (i.equalTime(arrivalQueue.peek())) {
59 waitQueue.enqueue(i.getCopy());
60 del=arrivalQueue.dequeue();
61 }
62
63 if ((machineWash==status.busy) && (i.equalTime(washEnd))) {
64 washEnd.setTime(14,0,0);
65 machineWash=status.free;
66 }
67
68 if ((machineWash==status.free) && !(waitQueue.isEmpty())) {
69 washStart=i.getCopy();
70 washEnd=i.getCopy(); washEnd.addTimeMinute(5);
71 doAnalysis(i,waitQueue.peek(),washEnd); // call doAnalysis method
72 del=waitQueue.dequeue();
73 machineWash=status.busy;
74 }
75
76 if ((machineWash==status.free) && (waitQueue.isEmpty()))
77 washEnd.setTime(14,0,0);
78
79 //jump to next event.
80 if (!arrivalQueue.isEmpty())
81 if (washEnd.lessThan(arrivalQueue.peek())) {
82 i=washEnd.getCopy();
83 }
84 else {
85 i=arrivalQueue.peek().getCopy();
86 }
87 else {
88 i=washEnd.getCopy();
89 }
90 }
91
92 //report
93 System.out.print("\nREPORT\n");
94 System.out.print("Number of customer arrive by 8.30 am: " + numCar + "\n");
95 System.out.print("Longest waiting time: " + maxDur + " minutes\n");
96 System.out.print(String.format("Average waiting time: %.2f minutes",
97 totalWait/(float)numCar));
98 }
99
100
101 public static void doAnalysis(Clock waitStop, Clock start, Clock washStop) {
102
103 int carWait,machineWork;
104
105 carWait=start.durationSec(waitStop.getCopy());
106 machineWork=waitStop.durationSec(washStop.getCopy());
107 numCar++;
108 totalWait+= carWait;
109 totalWork+=machineWork;
110 if (maxDur<carWait)
111 maxDur=carWait;
112 }
113 }
114
Queue 18
Self-activity
Tutorial Activity
Hands-on Activity
Implement the worked-example of ABC Wash Machine program. Try to understand the output printed by the
program.
Queue 19
Problem: Extension of ABC Wash Machine
Problem Description
The DEF Wash Machine problem will use the same problem description as the worked-example of ABC Wash
Machine with regard the DEF Wash Machine provides two types of services:
Type 1: normal wash (takes 6 minutes for every service)
Type 2: wash and polish (takes 10 minutes for every service).
The owner of the DEF Wash Machine would like to know the statistical information as below:
Total customers: <total_customer>
Number of customers for service of type 1: <Number_ customer _type_1>
Number of customers for service of type 2: <Number_ customer _type_2>
Longest customer waiting time: < Longest_waiting_time>
Average customer waiting time: < Average_waiting_time>
Your task is to modify the worked-example of ABC Wash Machine and print out the above statistical
information.
Input
Input are randomly generated.
Sample Output
Total customers:
Number of customers for service of type 1: <Number_ customer _type_1>
Number of customers for service of type 2: <Number_ customer _type_2>
Longest customer waiting time: < Longest_waiting_time>
Average customer waiting time: < Average_waiting_time>
Queue 20
Tips
1. Queue in DEF Wash Machine problem holds two information: arrival time and service type. So, we
would like to suggest you to use class Customer as follows:
public Customer()
{
time.setTime(0,0,0);
serviceType =0;
}
return temp;
}
return temp;
}
temp.time = time.getCopy();
temp.serviceType= getSeviceType();
temp.toString();
return temp;
}
str = this.time.toString();
str = str + " (" + serviceType + ") ";
return str;
}
}
Queue 21
2. Be careful with your variable WashEnd. (Why?)
3. Manipulation of a queue which hold single information is simple. However, queue which hold complex
information such as class Customer is not easy to handle. Hence, we give you code example on how
to manipulate this type of queue.
myQueue.enqueue(car.CopyCustomer());
if(arrivalQueue.peek().serviceType==2)
System.out.print("service type is 2- Wash Only" );
Produce report.
Queue 22
Tutorial Activity
Queue 23
Other Applications of Queue
Beside the service simulation problem, queue is also used in many other applications. Some of the examples
are as below:
1. In a computer systems, queue is used as a “holding area” for messages between two processes, two
programs, or even two systems.
2. Serving requests of a single shared resource (printer, disk, CPU)
3. Center phone systems will use a queue to hold people in line until a service is available.
Queue 24