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

43 lines
1.3 KiB
Java

import java.util.concurrent.atomic.AtomicBoolean;
public class TAS {
static AtomicBoolean occupied = new AtomicBoolean(false);
public static void main(String[] args) {
Thread t1 = new Thread(new Proc2(), "1");
Thread t0 = new Thread(new Proc2(), "0");
t1.start();
t0.start();
}
}
class Proc2 implements Runnable {
int id; // identifiant du Thread
public void run() {
id = Integer.parseInt(Thread.currentThread().getName());
while (true) { // SC = Section Critique
System.out.println("Thread " + id + " est hors SC");
entrer();
System.out.println("Thread " + id + " est en SC");
sortir();
}
}
void entrer() {
System.out.println("Thread " + id + " veut entrer en SC ");
while (!TAS.occupied.compareAndSet(false, true)) {
System.out.println(
(char) 27 + "[0;90m" + "Thread " + id + " attend que TAS ne soit plus occupé" + (char) 27 + "[0m");
}
System.out.println("Thread " + id + " est entré en SC ");
}
void sortir() {
System.out.println("Thread " + id + " sort de SC ");
TAS.occupied.set(false);
System.out.println("Thread " + id + " est sortit de SC ");
}
}