Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package AirportPkg;
- import java.util.LinkedList;
- import java.util.Queue;
- public class Airport extends Thread {
- private boolean isOpen;
- private Queue<Airplane> waitingAirplanes;
- private AirportCaller myCaller; // to get airplanes
- public Airport() throws InterruptedException {
- isOpen = true;
- waitingAirplanes = new LinkedList<Airplane>();
- Utils.printLog("Tower", "Airport started to work\n");
- this.start();
- myCaller = new AirportCaller(this);
- }
- public boolean isOpen() {
- return this.isOpen;
- }
- public void close() throws InterruptedException {
- // stop getting new airplanes
- myCaller.stopCalling();
- myCaller.join();
- Utils.printLog("Tower",
- "* * * * * Airport is going to be closed. * * * * *\n");
- Utils.printLog("Tower", "new calls are not allowed.");
- // close airport
- isOpen = false;
- // stop waiting for airplanes
- synchronized (this) {
- this.notify();
- }
- }
- // airplane is calling the airport to land or take off
- public synchronized void newCall(Airplane airplane) {
- Utils.printLog("Call", airplane + " is calling the airport.");
- waitingAirplanes.add(airplane);
- Utils.printLog("Tower", airplane
- + " Wellcome to airport. wait for permission.");
- Utils.printLog("wait",
- airplane + " is waiting to " + airplane.getFinalState());
- if (waitingAirplanes.size() == 1) {
- // now airport has waiting airplanes, stop waiting
- synchronized (this) {
- this.notify();
- }
- }
- }
- @Override
- public void run() {
- while (isOpen || !waitingAirplanes.isEmpty()) {
- if (waitingAirplanes.isEmpty() && isOpen) {
- // airport is empty while its open
- // wait for new call from an airplane
- synchronized (this) {
- try {
- Utils.printLog("Tower",
- "Airport is empty. waiting for airplanes . . .\n");
- this.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- Airplane activeAirplane = waitingAirplanes.poll();
- if (activeAirplane != null) {
- // giving permission to airplane
- synchronized (activeAirplane) {
- Utils.printLog("Tower",
- activeAirplane + ", you have permition to "
- + activeAirplane.getFinalState());
- activeAirplane.notify();
- try {
- // wait for airplane to finish
- activeAirplane.join();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Utils.printLog("Tower", "continue to next airplane . . .\n");
- }
- }
- }
- Utils.printLog("Tower", "Airport is now empty.\n");
- Utils.printLog("Tower", "Airport is now closed.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement