算法Sedgewick第四版-第1章基础-024-M/M/1 queue

 1 /******************************************************************************
 2  *  Compilation:  javac MM1Queue.java
 3  *  Execution:    java MM1Queue lambda mu
 4  *  Dependencies: Queue.java Histogram.java
 5  *
 6  *  Simulate an M/M/1 queue where arrivals and departures are Poisson
 7  *  processes with arrival rate lambda and service rate mu.
 8  *
 9  *  % java MM1Queue .20 .33
10  *
11  *  % java MM1Queue .20 .25 
12  *
13  *  % java MM1Queue .20 .21
14  *
15  *
16  *  Remarks
17  *  -------
18  *   - We assume the interrarrival and service times are independent.
19  * 
20  *
21  ******************************************************************************/
22 
23 public class MM1Queue { 
24 
25     public static void main(String[] args) { 
26         double lambda = Double.parseDouble(args[0]);  // arrival rate
27         double mu     = Double.parseDouble(args[1]);  // service rate
28 
29         Queue<Double> q = new Queue<Double>();            // arrival times of customers
30         double nextArrival   = StdRandom.exp(lambda);     // time of next arrival
31         double nextDeparture = Double.POSITIVE_INFINITY;  // time of next departure
32 
33         // histogram object
34         Histogram hist = new Histogram(60);
35 
36         // simulate an M/M/1 queue
37         while (true) {
38 
39             // it's an arrival
40             if (nextArrival <= nextDeparture) {
41                 if (q.isEmpty()) nextDeparture = nextArrival + StdRandom.exp(mu);
42                 q.enqueue(nextArrival);
43                 nextArrival += StdRandom.exp(lambda);
44             }
45 
46             // it's a departure
47             else {
48                 double wait = nextDeparture - q.dequeue();
49                 StdOut.printf("Wait = %6.2f, queue size = %d
", wait, q.size());
50                 hist.addDataPoint(Math.min(60,  (int) (Math.round(wait))));
51                 hist.draw();
52                 if (q.isEmpty()) nextDeparture = Double.POSITIVE_INFINITY;
53                 else             nextDeparture += StdRandom.exp(mu);
54                 
55             }
56         }
57 
58     }
59 
60 }
原文地址:https://www.cnblogs.com/shamgod/p/5411993.html