This commit is contained in:
Luca Conte 2025-04-23 22:56:48 +02:00
parent 64fc30d444
commit 1d75699c81
3 changed files with 86 additions and 0 deletions

32
u06_3/Philosopher.java Normal file
View File

@ -0,0 +1,32 @@
class Philosopher implements Runnable {
private Table t;
private int id;
public Philosopher(Table t, int id) {
this.t = t;
this.id = id;
}
public void talk() {
System.out.println("Philosopher " + this.id + " is talking.");
}
public void eat() {
System.out.println("Philosopher " + this.id + " is eating.");
}
public void run() {
talk();
try {
t.takeForks(this.id);
} catch (InterruptedException e) {
e.printStackTrace();
}
eat();
t.returnForks(this.id);
}
}

View File

@ -0,0 +1,21 @@
class PhilosophersTest {
public static void main(String[] args) {
int numPhilosophers = 5;
Thread[] philosophers = new Thread[numPhilosophers];
Table t = new Table(numPhilosophers);
for (int i = 0; i < numPhilosophers; i++) {
philosophers[i] = new Thread(new Philosopher(t, i));
philosophers[i].start();
}
for (int i = 0; i < numPhilosophers; i++) {
try {
philosophers[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

33
u06_3/Table.java Normal file
View File

@ -0,0 +1,33 @@
import java.util.concurrent.Semaphore;
class Table {
private int numForks;
private Semaphore[] forks;
public Table(int numForks) {
this.numForks = numForks;
this.forks = new Semaphore[numForks];
for (int i = 0; i < this.numForks; i++) {
this.forks[i] = new Semaphore(1);
}
}
public void takeForks(int i) throws InterruptedException {
int left = i;
int right = (i + 1) % numForks;
if (right > left) {
forks[left].acquire();
forks[right].acquire();
} else {
forks[right].acquire();
forks[left].acquire();
}
}
public void returnForks(int i) {
forks[i].release();
forks[(i + 1) % numForks].release();
}
}