TP-systemes-concurrents/TP3/PhiloSem2.java
2023-06-21 20:19:26 +02:00

64 lines
1.8 KiB
Java

import java.util.concurrent.Semaphore;
public class PhiloSem2 implements StrategiePhilo {
/****************************************************************/
int nbPhilosophe;
int fg, fd;
Semaphore[] fourchettes;
public PhiloSem2(int nbPhilosophes) {
this.nbPhilosophe = nbPhilosophes;
this.fourchettes = new Semaphore[Main.nbPhilosophes];
for (int i = 0; i < fourchettes.length; i++) {
fourchettes[i] = new Semaphore(1, true);
}
}
/**
* Le philosophe no demande les fourchettes. Précondition : il n'en possède
* aucune. Postcondition : quand cette méthode retourne, il possède les deux
* fourchettes adjacentes à son assiette.
*/
public void demanderFourchettes(int no) throws InterruptedException {
int fg = Main.FourchetteGauche(no);
int fd = Main.FourchetteDroite(no);
fourchettes[fd].acquire();
IHMPhilo.poser(fd, EtatFourchette.AssietteGauche);
Thread.sleep(10000);
fourchettes[fg].acquire();
IHMPhilo.poser(fg, EtatFourchette.Table);
}
/**
* Le philosophe no rend les fourchettes. Précondition : il possède les deux
* fourchettes adjacentes à son assiette. Postcondition : il n'en possède
* aucune. Les fourchettes peuvent être libres ou réattribuées à un autre
* philosophe.
*/
public void libererFourchettes(int no) {
int fd = Main.FourchetteDroite(no);
fourchettes[fd].release();
IHMPhilo.poser(fd, EtatFourchette.Table);
int fg = Main.FourchetteGauche(no);
fourchettes[fg].release();
IHMPhilo.poser(fg, EtatFourchette.Table);
}
/** Nom de cette stratégie (pour la fenêtre d'affichage). */
public String nom() {
return "Sémaphores, strat 2: interblocage obligé";
}
}