#java #multithreading #concurrency
Вопрос:
Я разрабатываю симуляцию аэропорта и столкнулся с трудностями. Я пытаюсь спроектировать, когда самолеты получили доступ к 4 воротам, поток ATC отобразит вывод о том, что ворота заполнены (например: ворот не осталось). Так или иначе, в моем выводе есть ошибка…
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.OptionalInt;
import java.util.Random;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
Runway runway= new Runway();
for(int i=1 ; i<= 10 ; i )
{
Plane p = new Plane(i, runway);
p.start();
}
ATC atc= new ATC(runway);
atc.start();
}
}
public class Plane extends Thread{
Runway runway;
int id;
Plane(int id, Runway runway)
{
this.id = id;
this.runway = runway;
}
@Override
public void run()
{
try {
runway.required_to_land(this);
} catch (InterruptedException ex) {
Logger.getLogger(Plane.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class ATC extends Thread{
Runway runway;
public ATC(Runway runway)
{
this.runway= runway;
}
@Override
public void run()
{
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(ATC.class.getName()).log(Level.SEVERE, null, ex);
}
while(!runway.maybeGateNumber.isPresent())
{
System.out.println("ATC: There is no gates left!");
}
}
}
public class Runway {
final Deque<Integer> availableGates = new ArrayDeque<>(Arrays.asList(1, 2, 3, 4));
OptionalInt claimGate() {
synchronized (availableGates) {
if (availableGates.isEmpty()) {
// You need to handle the possibility of no gates.
return OptionalInt.empty();
}
return OptionalInt.of(availableGates.removeFirst());
}
}
void releaseGate(int gateNumber) {
synchronized (availableGates) {
availableGates.add(gateNumber);
}
}
void required_to_land(Plane plane) throws InterruptedException
{
Thread.sleep(new Random().nextInt(3000));
System.out.println("Plane " plane.id " requests to land!");
Thread.sleep(500);
access_runway(plane);
}
OptionalInt maybeGateNumber;
void access_runway(Plane plane) throws InterruptedException
{
int gateNumber;
synchronized(this){
maybeGateNumber = claimGate();
System.out.println("Plane " plane.id " is accessing the runway!");
Thread.sleep(1000);
gateNumber = maybeGateNumber.getAsInt();
System.out.println("Plane " plane.id " has landed at gate " gateNumber "!");
}
access_gate(plane, gateNumber);
}
void access_gate(Plane plane, int gateNumber) throws InterruptedException
{
Thread.sleep(new Random().nextInt(8000));
System.out.println("Plane " plane.id " had left gate " gateNumber "!");
releaseGate(gateNumber);
}
}
Ниже приведен мой результат!
Plane 2 requests to land!
Plane 6 requests to land!
Plane 2 is accessing the runway!
Plane 8 requests to land!
Plane 1 requests to land!
Plane 2 has landed at gate 1!
Plane 8 is accessing the runway!
Plane 4 requests to land!
Plane 3 requests to land!
Plane 7 requests to land!
Plane 8 has landed at gate 2!
Plane 6 is accessing the runway!
Plane 5 requests to land!
Plane 10 requests to land!
Plane 9 requests to land!
Plane 6 has landed at gate 3!
Plane 9 is accessing the runway!
Plane 9 has landed at gate 4!
Plane 10 is accessing the runway!
Plane 5 is accessing the runway!
Exception in thread "Thread-9" java.util.NoSuchElementException: No value present
at java.util.OptionalInt.getAsInt(OptionalInt.java:118)
at assignment_self.Runway.access_runway(Runway.java:62)
at assignment_self.Runway.required_to_land(Runway.java:41)
at assignment_self.Plane.run(Plane.java:21)
Plane 7 is accessing the runway!
Exception in thread "Thread-4" java.util.NoSuchElementException: No value present
at java.util.OptionalInt.getAsInt(OptionalInt.java:118)
at assignment_self.Runway.access_runway(Runway.java:62)
at assignment_self.Runway.required_to_land(Runway.java:41)
at assignment_self.Plane.run(Plane.java:21)
Plane 8 had left gate 2!
Plane 3 is accessing the runway!
Exception in thread "Thread-6" java.util.NoSuchElementException: No value present
at java.util.OptionalInt.getAsInt(OptionalInt.java:118)
at assignment_self.Runway.access_runway(Runway.java:62)
at assignment_self.Runway.required_to_land(Runway.java:41)
at assignment_self.Plane.run(Plane.java:21)
Plane 6 had left gate 3!
Plane 3 has landed at gate 2!
Plane 4 is accessing the runway!
Plane 2 had left gate 1!
Plane 9 had left gate 4!
Plane 4 has landed at gate 3!
Plane 1 is accessing the runway!
Plane 1 has landed at gate 1!
Plane 4 had left gate 3!
Plane 1 had left gate 1!
Plane 3 had left gate 2!
Было бы здорово, если бы кто — нибудь смог мне помочь! Заранее благодарю вас!
Комментарии:
1. Я голосую за то, чтобы закрыть этот вопрос. Я полагаю , основан на коде комментария, который говорит: «Вы должны обращаться возможности без ворот», что ваш пример кода точно так, как он был дан вам в учителя, и что ваша задача-это изменить его, чтобы сделать что-то более значимое, чем бросать исключение, когда все ворота заняты. Мне кажется, что вы просите нас сделать за вас домашнее задание. ИМО, возможно, вы захотите спросить себя, что бы настоящий диспетчер аэропорта сказал пилоту приближающегося самолета делать, если бы на пандусе не было свободного места для парковки?
2. P.S., Если вы используете аксинг, как
Runway#access_runway()
узнать, был ли назначен вход, он может позвонитьmaybeGateNumber.isPresent()
. Это вернется вtrue
случаеclaimGate()
успеха илиfalse
неудачи.