mmayoub

Airport system, Airplane class

Aug 25th, 2017
131
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package AirportPkg;
  2.  
  3. public class Airplane extends Thread {
  4.     // final state for an airplane
  5.     public enum AirplaneState {
  6.         TakeOff, Land
  7.     }
  8.  
  9.     private static int autoId = 100;
  10.  
  11.     private Airport airport;
  12.     private AirplaneState finalState;
  13.     private int flightNo;
  14.  
  15.     public Airplane(Airport airport) {
  16.         this.airport = airport;
  17.         this.finalState = Utils.getRandomState();
  18.  
  19.         autoId += 1;
  20.         this.flightNo = Airplane.autoId;
  21.  
  22.         this.start();
  23.     }
  24.  
  25.     public AirplaneState getFinalState() {
  26.         return this.finalState;
  27.     }
  28.  
  29.     public int getFlightNo() {
  30.         return this.flightNo;
  31.     }
  32.  
  33.     @Override
  34.     public void run() {
  35.         synchronized (this) {
  36.             try {
  37.                 // waiting to get permission from airport
  38.                 wait();
  39.  
  40.                 int time = this.getTime();
  41.                 Utils.printLog("Start", this + " start to " + finalState
  42.                         + " for " + time + "ms");
  43.  
  44.                 // airplane is flying. all others should wait
  45.                 Thread.sleep(this.getTime());
  46.  
  47.                 Utils.printLog("End", this + " has finished to " + finalState);
  48.  
  49.                 // notify airport to continue
  50.                 synchronized (airport) {
  51.                     this.airport.notify();
  52.                 }
  53.             } catch (InterruptedException e) {
  54.                 // TODO Auto-generated catch block
  55.                 e.printStackTrace();
  56.             }
  57.         }
  58.     }
  59.  
  60.     // get random time for this airplane to land or takeoff
  61.     private int getTime() {
  62.         if (this.finalState == AirplaneState.Land)
  63.             return Utils.getLandingTime();
  64.  
  65.         if (this.finalState == AirplaneState.TakeOff)
  66.             return Utils.getTakingOffTime();
  67.  
  68.         return 0;
  69.     }
  70.  
  71.     @Override
  72.     public String toString() {
  73.         // TODO Auto-generated method stub
  74.         return "Airplane #" + this.flightNo;
  75.     }
  76. }
RAW Paste Data