Presentation is loading. Please wait.

Presentation is loading. Please wait.

Queues Chapter 6 Chapter 6: Queues2 Chapter Objectives Learn how to represent a “waiting line”, i.e., a queue Learn how to use the methods in the Queue.

Similar presentations


Presentation on theme: "Queues Chapter 6 Chapter 6: Queues2 Chapter Objectives Learn how to represent a “waiting line”, i.e., a queue Learn how to use the methods in the Queue."— Presentation transcript:

1

2 Queues Chapter 6

3 Chapter 6: Queues2 Chapter Objectives Learn how to represent a “waiting line”, i.e., a queue Learn how to use the methods in the Queue interface Insertion (offer and add) Removal (remove and poll) Accessing front element (peek and element) Understand how to implement the Queue interface Double-linked list, single-linked list, circular array Understand how to simulate the operation of a physical system that has one or more waiting lines using queues Also using random number generators

4 Chapter 6: Queues3 Queue Abstract Data Type A line of customers waiting for service is a queue Q: Who is served next? A: The person who has waited the longest Q: Where do new arrivals go? A: The end of the queue (line)

5 Chapter 6: Queues4 Uses for Queues Operating systems use queues to manage tasks involving scarce resource Q: Why a queue? A: To ensure that the tasks are carried out in the order that they were generated For example, a print queue Printing is much slower than selecting pages to print

6 Chapter 6: Queues5 Print Queue

7 Chapter 6: Queues6 Unsuitability of a Print Stack Stacks are last-in, first-out (LIFO) Most recently selected document would be next to print Unless the printer queue is empty, your print job may never get executed if others are issuing print jobs Queue is better choice for printing Queue since first in, first out (FIFO) “Oldest” selected document gets printed next Much fairer than “print stack”

8 Chapter 6: Queues7 Queues Used to Traverse Graphs A graph models a network of nodes, with many links connecting each node to other nodes in the network A node in a graph may have several successors Can use a queue to ensure that nodes closer to the starting point are visited before nodes farther away We will see this later…

9 Chapter 6: Queues8 Specification for a Queue Interface

10 Chapter 6: Queues9 LinkedList Implements Queue Interface LinkedList provides methods for inserting and removing elements at either end of a double-linked list Java 5.0 LinkedList class implements Queue interface Queue names = new LinkedList (); creates Queue reference, names (in this example, stores references to String objects) The actual object referenced by names is type LinkedList Because names is a type Queue reference, you can apply only the Queue methods to it

11 Chapter 6: Queues10 Queue Examples Consider Queue names = new LinkedList (); Suppose names currently contains Where “Dorothy” was 1st into the queue Dorothy Toto Scarecrow Tinman Lion

12 Chapter 6: Queues11 Queue Examples Suppose names currently contains What do each of the following do? String first = names.peek(); String first = names.element(); Dorothy Toto Scarecrow Tinman Lion

13 Chapter 6: Queues12 Queue Examples Suppose names currently contains What do each of the following do? String temp = names.remove(); String temp = names.poll(); Dorothy Toto Scarecrow Tinman Lion

14 Chapter 6: Queues13 Queue Examples Suppose names currently contains What do both of the following do? names.offer(“Wizard”); names.add(“Wizard”); Toto Scarecrow Tinman Lion

15 Chapter 6: Queues14 Queue Examples Then names contains Assuming that only offer or add executed (not both) Toto Scarecrow Tinman Lion Wizard

16 Chapter 6: Queues15 Case Study: A Queue of Customers Problem: Write menu-driven program that maintains a queue of customers waiting for service. Program must be able to Insert new customer in line Remove customer who is next in line Display length of the line Determine a specific customers place in line

17 Chapter 6: Queues16 Case Study: A Queue of Customers Analysis: Queue is the obvious choice… Use JOptionPane for dialog menus Inputs: Operation to be performed Name of a customer Outputs: Effect of each operation

18 Chapter 6: Queues17 Case Study: A Queue of Customers Design: Class MaintainQueue with Queue component, customers Method processCustomers displays menu choices and processes input

19 Chapter 6: Queues18 Case Study: A Queue of Customers

20 Chapter 6: Queues19 Case Study: A Queue of Customers Algorithm for processCustomers While the user is not finished Display menu and get selected operation Perform selected operation Each operation requires call to a Queue method Except for finding customer’s place in line How to do this?

21 Chapter 6: Queues20 Case Study: A Queue of Customers Algorithm for position in queue Get customer’s name Set count of customers ahead to 0 For each customer in the queue If customer is not specified customer Increment count Else Display count and exit loop If all customers examined without success Display message that customer is not in line

22 Chapter 6: Queues21 Case Study: A Queue of Customers Class file MaintainQueue.java is in the book and at http://www.cs.sjsu.edu/~stamp/CS46B/other/queue/

23 Chapter 6: Queues22 Queue Implementations We consider 3 different implementations: Double-linked list This is what Java designers used Single-linked list Similar to using double-linked list Circular array Most efficient approach (in terms of space) But somewhat more complex

24 Chapter 6: Queues23 Double-Linked List Queue Implemention Insertion and removal from either end of a double-linked list is O(1) So either end can be the front (or rear) of the queue Which would you choose? Java makes head of the linked list front of queue So tail is the rear of the queue Issue: LinkedList object is used as a queue Why is this an “issue”? May be possible to apply other LinkedList methods In addition to the ones required by the Queue interface

25 Chapter 6: Queues24 Single-Linked List Queue Implementation Can implement a queue using a single-linked list Book gives Class ListQueue Contains a collection of Node objects Which end should be front of queue? Front makes sense, that is… insertions are at the rear of a queue and… removals are from the front Want to have a reference to the last list node (why?) Number of elements changed by insert and remove Empty queue is a special case

26 Chapter 6: Queues25 Single-Linked List Queue Implementation

27 Chapter 6: Queues26 Circular Array Queue Implementation Time efficiency of using a single- or double-linked list to implement a queue is O(1) However there are some space inefficiencies Storage space is increased when using a linked list due to references stored at each list node Array Implementation: Front and rear? Insertion at rear of array is constant time But them removal from the front is linear time (why?) Removal from rear of array is constant time But then insertion at the front is linear time (why?)

28 Chapter 6: Queues27 Circular Array Queue Implementation

29 Chapter 6: Queues28 Circular Array Queue Implementation

30 Chapter 6: Queues29 Circular Array Queue Implementation

31 Chapter 6: Queues30 Circular Array Queue Implementation How to access elements in circular array? Use “mod” operator: % For example, to insert (at rear): rear = (rear + 1) % capacity;

32 Chapter 6: Queues31 Clock Arithmetic 2 1 5 4 3 arithmetic mod 6 For integers x and n, “x mod n” is the remainder of x  n In Java, “x mod n” is: x % n Examples 7 mod 6 = 1 33 mod 5 = 3 33 mod 6 = 3 51 mod 17 = 0 17 mod 6 = 5

33 Chapter 6: Queues32 Circular Array Queue Implementation

34 Chapter 6: Queues33 Circular Array Queue Implementation Why not use System.arraycopy to copy elements when reallocating circular array? System.arraycopy(theData, 0, newData, 0, capacity) This will not work! Consider Toto Scarecrow Tinman Lion Wizard front rear 0 1 2 3 4

35 Chapter 6: Queues34 Circular Array Queue Implementation Suppose to reallocate, we try System.arraycopy(theData, 0, newData, 0, capacity) In this case… Toto Scarecrow Tinman Lion Wizard front rear 0 1 2 3 4 Toto Scarecrow Tinman Lion Wizard front rear 0 1 2 3 4 5 6 7 8 9

36 Chapter 6: Queues35 Implementing Class ArrayQueue.Iter To fully implement the Queue interface… We must implement the missing Queue methods And an inner class Iter Field index has subscript of the next element to access The constructor initializes index to front when a new Iter object is created Data field count keeps track of the number of items accessed so far Method Iter.remove throws Unsupported-OperationException Would violate “contract” by removing item other than 1st

37 Chapter 6: Queues36 Comparing 3 Queue Implementations All three are O(1), i.e., constant time What about reallocate in circular array? But linked lists require more storage: Why? Extra space for links! Node for single-linked list stores two references Node for double-linked list stores three references How much better is circular array? If filled to capacity, requires half the storage of a single-linked list to store same number of elements

38 Chapter 6: Queues37 Simulating Waiting Lines Using Queues Simulations used to study the performance of systems Can Use math and/or computer model of system Simulations allow designers of system to estimate performance and/or characteristics before building it Simulation can lead to changes in the design that will improve a proposed system Simulation is useful, for example, when real system is too expensive to build too dangerous to experiment with

39 Chapter 6: Queues38 Airline Check-In Counter Simulation Two lines/queues: regular passenger and frequent flyers Only one ticket agent How to serve the 2 lines? Democratic strategy: alternate between lines Another democratic strategy: serve longest waiting Elitist approach: serve frequent flyers first Combination strategies Queuing theory can be used to analyze this problem Mathematical theory  also used to study networks Here, we use a computer simulation

40 Chapter 6: Queues39 Airline Check-In Counter Simulation

41 Chapter 6: Queues40 Airline Check-In Counter Simulation Problem: Wizard of Oz Airlines is considering redesigning its ticket counter operations Assumptions include One ticket agent Two lines of customers (regular, frequent flyers) Want to experiment with various strategies Democratic, elitist, combinations thereof Want to know effect on waiting time for both lines, under various assumptions on arrival rates

42 Chapter 6: Queues41 Airline Check-In Counter Simulation Analysis: Computer simulation is a good idea, since difficult to study many alternatives in real world situation Must keep track of “time” Types of “events” that can occur: New frequent flyer arrives in line New regular passenger arrives in line Ticket agent finishes serving someone and begins serving frequent flyer Ticket agent finishes serving someone and begins serving regular passenger Ticket agent is idle (no passengers to serve)

43 Chapter 6: Queues42 Airline Check-In Counter Simulation Analysis (continued): Purpose is to generate statistics on waiting time for passengers Also, we can display minute-by-minute trace Useful for debugging Results will depend on Priority given to frequent flyers Arrival rate of each type of passenger Time required to serve each passenger

44 Chapter 6: Queues43 Airline Check-In Counter Simulation Design: Want to identify the objects Look at the nouns: Agent, passengers, passenger lines, simulation Gives us the following UML diagram We will use a queue to represent the “lines” (surprised?)

45 Chapter 6: Queues44 Airline Check-In Counter Simulation Sequence diagram Shows the flow between objects Also, data that is passed

46 Chapter 6: Queues45 Airline Check-In Counter Simulation Sequence diagram tells us agent is either busy or idle Also tells us the methods needed in each class Revise UML diagram

47 Chapter 6: Queues46 Class AirlineCheckinSim

48 Chapter 6: Queues47 Class AirlineCheckinSim

49 Chapter 6: Queues48 Class PassengerQueue

50 Chapter 6: Queues49 Class PassengerQueue

51 Chapter 6: Queues50 Class Passenger This class stores following info about a passenger Unique ID number Time at which passenger arrived Processing time Maximum processing time Note that “ID number” is just the position in queue

52 Chapter 6: Queues51 Class Passenger

53 Chapter 6: Queues52 Input Parameters

54 Chapter 6: Queues53 Pseudorandom Numbers How to generate “random” numbers? In the real world, flip a coin, roll a die, etc. In computer simulation, use “pseudorandom” numbers Generated in sequence Based on an initial “seed” value Note that same seed yields same sequence Why is this useful (necessary) for computer simulation? Not really “random”, so pseudorandom But these numbers have nice statistical properties

55 Chapter 6: Queues54 Pseudorandom Numbers Our airline simulation uses pseudorandom numbers to… Determine whether a passenger has arrived within a given minute of simulation Determine how long it takes to serve a passenger Suppose passengers arrival rate is 1 every 5 minutes Do passengers arrive precisely at 0,5,10,15,… ? No! On average, one arrives every 5 minutes How to simulate this?

56 Chapter 6: Queues55 Pseudorandom Numbers Suppose passengers arrival rate is 1 every 5 minutes For a given 1 minute time interval of simulation Generate pseudorandom number between 0 and 1 If generated number less than 0.2, then passenger arrived in that interval Else no passenger arrived Suppose arrivalRate is rate at which passengers arrive (per minute) Then, in Java, passenger arrives if Math.random() < arrivalRate Otherwise, no passenger arrives

57 Chapter 6: Queues56 Airline Check-In Counter Simulation Code http://www.cs.sjsu.edu/~stamp/CS46B/other/queue/airline/

58 Chapter 6: Queues57 Chapter Review Queue is an abstract data type with a first-in, first-out structure (FIFO) The Queue interface declares methods offer, remove, poll, peek, and element. Three ways to implement the Queue interface: double- linked list, single-linked list, and circular array To avoid the cost of building a physical system or running an actual experiment, computer simulation can be used to evaluate the expected performance of a system or operation strategy


Download ppt "Queues Chapter 6 Chapter 6: Queues2 Chapter Objectives Learn how to represent a “waiting line”, i.e., a queue Learn how to use the methods in the Queue."

Similar presentations


Ads by Google