From 1d75699c81ee0a1eacb4d5e391a3203d9a31c396 Mon Sep 17 00:00:00 2001 From: Luca Conte Date: Wed, 23 Apr 2025 22:56:48 +0200 Subject: [PATCH] u06-3 --- u06_3/Philosopher.java | 32 ++++++++++++++++++++++++++++++++ u06_3/PhilosophersTest.java | 21 +++++++++++++++++++++ u06_3/Table.java | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 u06_3/Philosopher.java create mode 100644 u06_3/PhilosophersTest.java create mode 100644 u06_3/Table.java diff --git a/u06_3/Philosopher.java b/u06_3/Philosopher.java new file mode 100644 index 0000000..fc237c2 --- /dev/null +++ b/u06_3/Philosopher.java @@ -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); + } +} \ No newline at end of file diff --git a/u06_3/PhilosophersTest.java b/u06_3/PhilosophersTest.java new file mode 100644 index 0000000..b489cb5 --- /dev/null +++ b/u06_3/PhilosophersTest.java @@ -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(); + } + } + } +} \ No newline at end of file diff --git a/u06_3/Table.java b/u06_3/Table.java new file mode 100644 index 0000000..de88045 --- /dev/null +++ b/u06_3/Table.java @@ -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(); + } +} \ No newline at end of file