diff --git a/src/train/Railway.java b/src/train/Railway.java index 92b2a99587c0995c985e43e374f399fab1038ca1..3f9d668daa27c4daf0ba175199de93c05f78a7b6 100644 --- a/src/train/Railway.java +++ b/src/train/Railway.java @@ -12,6 +12,9 @@ public class Railway { private final Element[] elements; private Direction currentDirection = null; //Paramètre pour controller la direction actuelle des trains en circulation private int movingTrains = 0; //Nombre de trains en circulations + private int trainsWaitingRL = 0; + private int trainsWaitingLR = 0; + public Railway(Element[] elements) { if(elements == null) @@ -55,13 +58,24 @@ public class Railway { } public synchronized void requestToMove(Train t, Direction d) throws InterruptedException { - while (movingTrains > 0 && currentDirection != d) { - wait(); // On attend si des trains circulent dans l'autre sens - } - // Autorisation de départ - currentDirection = d; - movingTrains++; - } + // Augmente le nombre de trains en attente + if (d == Direction.LR) trainsWaitingLR++; + else trainsWaitingRL++; + + // Attente si un train circule déjà en sens inverse + while (movingTrains > 0 && currentDirection != d && (trainsWaitingRL <= trainsWaitingLR)) { + wait(); + } + + // Réduit le nombre de trains en attente + if (d == Direction.LR) trainsWaitingLR--; + else trainsWaitingRL--; + + // Met à jour la direction actuelle + currentDirection = d; + movingTrains++; + } + public synchronized void trainStopped(Train t) { movingTrains--; diff --git a/src/train/Section.java b/src/train/Section.java index 5037976374d5ca7ee9f3ba2a920f4eb2704db1c7..f72f67ccc292b61aa5eac744d08ed73d2cb6db2c 100644 --- a/src/train/Section.java +++ b/src/train/Section.java @@ -18,22 +18,26 @@ public class Section extends Element { } public synchronized void enterSection(Train t, Direction d, Railway railway) throws InterruptedException { - railway.requestToMove(t, d); - while (currentTrain != null || (currentDirection != null && currentDirection != d)) { - wait(); // Attente si la section est occupée ou si la direction est opposée - } - currentTrain = t; - currentDirection = d; - } + railway.requestToMove(t, d); + + while (currentTrain != null || (currentDirection != null && currentDirection != d)) { + wait(); + } + + currentTrain = t; + currentDirection = d; + } + + + public synchronized void leaveSection(Train t, Railway railway) { + if (currentTrain == t) { + currentTrain = null; + currentDirection = null; + notifyAll(); // Réveille les trains bloqués + } + railway.trainStopped(t); + } - public synchronized void leaveSection(Train t, Railway railway) { - if (currentTrain == t) { - currentTrain = null; - currentDirection = null; // Réinitialiser la direction si la section est vide - notifyAll(); // Réveille les trains en attente - } - railway.trainStopped(t); - } }