0
我模擬一個跑道的機場。等待着陸並等待起飛的飛機有兩排隊列。一次只能在跑道上有一架飛機,在任何飛機起飛前,空中的所有飛機都必須降落。這裏是我到目前爲止(有,我會得到後襬脫別人沒用變量時,我敢肯定,我不需要他們):一個簡單的機場模擬
public class Runway<E> {
private LinkedBlockingQueue<Plane> takeoff;
private LinkedBlockingQueue<Plane> landing;
private LinkedBlockingQueue<Plane> runway;
private int planesLanded;
private int planesTookoff;
private double averageTakeOffWait;
private double averageLandWait;
private int totalTakeoffWait;
private int totalLandingWait;
private int planesWaitingToTakeOff;
private int planesWaitingToLand;
private int maxLandingQueueLength;
private int maxTakeOffQueueLength;
public int timeToLand = 5;
public int timeToTakeoff = 4;
public double landingProbability = .1;
public double takeOffProbability = .1;
public int simulationLength = 1440;
public Runway() {
takeoff = new LinkedBlockingQueue<>();
landing = new LinkedBlockingQueue<>();
runway = new LinkedBlockingQueue<>();
planesLanded = 0;
planesTookoff = 0;
averageTakeOffWait = 0;
averageLandWait = 0;
totalTakeoffWait = 0;
totalLandingWait = 0;
planesWaitingToTakeOff = 0;
planesWaitingToLand = 0;
maxLandingQueueLength = 0;
maxTakeOffQueueLength = 0;
//reset();
}
public void simulate(int duration, double takeoffRate, double landingRate, int landingTime, int takeoffTime) {
for(int count = 0; count < duration; count++) {
if(Math.random() < takeoffRate) {
Plane p = new Plane(landingTime, takeoffTime, count);
takeoff.offer(p);
}
if(Math.random() < landingRate) {
Plane p = new Plane(landingTime, takeoffTime, count);
landing.offer(p);
}
if(runway.size() == 0) {
if(landing.peek() != null) {
Plane landingPlane = landing.poll();
runway.offer(landingPlane);
planesLanded++;
int landTimeWaited = count - landingPlane.getArrivalTime();
totalLandingWait += landTimeWaited;
runway.poll();
} else if(takeoff.peek() != null) {
Plane takeoffPlane = takeoff.poll();
runway.offer(takeoffPlane);
planesTookoff++;
int takeoffTimeWaited = count - takeoffPlane.getArrivalTime();
totalLandingWait += takeoffTimeWaited;
runway.poll();
}
}
}
}
public void report() {
System.out.println(planesLanded + " planes have landed.");
System.out.println(planesTookoff + " planes have taken off.");
System.out.println(landing.size() + " planes still waiting to land.");
System.out.println(takeoff.size() + " planes still waiting to takeoff.");
System.out.println(1.0*totalTakeoffWait/planesTookoff + " average take off wait time.");
System.out.println(1.0*totalLandingWait/planesLanded + " average landing wait time.");
}
}
我的問題是,飛機勉強曾經有等待任何事情。隊列中沒有剩下任何飛機。我知道我必須以某種方式讓它在5分鐘內通過,然後下一架飛機才能做任何事情,但我該怎麼做?這裏是一個測試運行:
Runway myAirport = new Runway();
myAirport.simulate(1440, .1, .1, 5, 4);
myAirport.report();
146 planes have landed.
155 planes have taken off.
0 planes still waiting to land.
0 planes still waiting to takeoff.
0.0 average take off wait time.
0.14383561643835616 average landing wait time.
您可以使用Thread.sleep,它會使操作花費一些時間。添加完成後,您總是會執行runway.poll,因此也許在投票前,您可以使用睡眠。另外,因爲您使用.poll,跑道尺寸是否始終爲零?你也可以隨意製作。 – matt