TP-systemes-concurrents/TP2/Mutex/Peterson.java
2023-06-21 20:19:26 +02:00

46 lines
1.4 KiB
Java

public class Peterson {
static int tour = 0;
static boolean[] demande = { false, false };
public static void main(String[] args) {
Thread t1 = new Thread(new Proc(), "1");
Thread t2 = new Thread(new Proc(), "0");
t1.start();
t2.start();
}
}
class Proc implements Runnable {
int id; // identifiant du Thread
int di; // identifiant de l'autre Thread
public void run() {
id = Integer.parseInt(Thread.currentThread().getName());
di = (id + 1) % 2;
while (true) { // SC = Section Critique
System.out.println("Thread " + id + " est hors SC");
entrer();
System.out.println("Thread " + id + " est en SC");
sortir();
}
}
synchronized void entrer() {
System.out.println("Thread " + id + " veut entrer en SC ");
Peterson.demande[id] = true;
Peterson.tour = di;
while ((Peterson.tour != id) && (Peterson.demande[di])) {
System.out.println(
(char) 27 + "[0;90m" + "Thread " + id + " attend la fin SC du Thread " + di + (char) 27 + "[0m");
}
System.out.println("Thread " + id + " est entré en SC ");
}
synchronized void sortir() {
System.out.println("Thread " + id + " veut sortir de SC ");
Peterson.demande[id] = false;
System.out.println("Thread " + id + " est sortit de SC ");
}
}