Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- public class Main {
- public static void main(String[] args) {
- Random rnd = new Random();
- int count = 0;
- int[] speed = new int[]{300,500,800};
- Airplane[] airplane = new Airplane[20];
- Operator operator = new Operator(airplane);
- Ether ether = new Ether(airplane, operator);
- for (count = 0; count<20; count++)
- {
- // airplane[count] = new Airplane(speed[rnd.nextInt(speed.length)] / 60, count, ether);
- // airplane[count].start();
- new Airplane(speed[rnd.nextInt(speed.length)] , count, ether).start();
- }
- }
- }
- class Airplane extends Thread {
- int index;
- int distance;
- int route;
- int roundTime = 10; // поменять на сколько нужно
- int flyTime = 10; // поменять на сколько нужно
- Ether ether;
- public Airplane(int speed_, int index_, Ether ether) {
- this.index = index_;
- this.ether = ether;
- flyTime = (10 * 1000 * 60) / speed_;
- roundTime = 2 * flyTime;
- }
- public void round() {
- System.out.println("Airplane " + index +" is rounding" + " on " + distance + " " + route);
- try {
- sleep(roundTime);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- public void moveTo(int dist, int r) {
- System.out.println("Airplane " + index +" Moving to " + dist + " " + r);
- distance = dist;
- route = r;
- }
- public void move() {
- try {
- sleep(flyTime);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- @Override
- public void run() {
- while (distance != 151) {
- if (!ether.callOperator(this)) {
- round();
- } else {
- move();
- }
- }
- }
- }
- class Operator {
- Airplane[] airplanes;
- boolean [][] path;
- public Operator(Airplane[] airplanes) {
- this.airplanes = airplanes;
- path = new boolean[151][3];
- }
- private int tryFindFreeRoute(int distance) {
- if (!path[distance][0]) return 0;
- else if (!path[distance][1]) return 1;
- else if (!path[distance][2]) return 2;
- else return -1;
- }
- public boolean handle(Airplane airplane) {
- if (airplane.distance == 150) {
- path[airplane.distance][airplane.route] = false;
- airplane.moveTo(151, 0);
- return true;
- }
- int route = tryFindFreeRoute(airplane.distance +1);
- if (route == -1) return false;
- else {
- path[airplane.distance][airplane.route] = false;
- path[airplane.distance+1][route] = true;
- airplane.moveTo(airplane.distance + 1, route);
- return true;
- }
- }
- }
- class Ether {
- private Operator operator;
- private Airplane[] airplanes;
- public Ether(Airplane[] airplanes, Operator operator) {
- this.operator = operator;
- this.airplanes = airplanes;
- }
- public synchronized boolean callOperator(Airplane airplane) {
- return operator.handle(airplane);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement