From 28611e3e2f54ec438767cd0059ea219ba6b234aa Mon Sep 17 00:00:00 2001 From: Shahnam Javidnia <3015418@stud.hs-mannheim.de> Date: Sun, 4 May 2025 21:48:06 +0200 Subject: [PATCH] Random signal constructor --- .../src/main/java/pp/Philosopher.java | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java b/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java index c1514c1..636f3ad 100644 --- a/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java +++ b/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java @@ -3,6 +3,7 @@ package pp; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Condition; import static pp.PhilosopherExperiment.*; +import java.util.Random; public class Philosopher extends Thread implements IPhilosopher { @@ -13,6 +14,13 @@ public class Philosopher extends Thread implements IPhilosopher { private Condition canEat; private volatile boolean eating = false; private volatile boolean stopped = false; + private final Random random; + + public Philosopher() { + this.random = new Random(); + this.seat = 0; + this.stopped = false; + } @Override public void setLeft(IPhilosopher left) { @@ -71,15 +79,15 @@ public class Philosopher extends Thread implements IPhilosopher { try { eating = false; log(seat, "hat fertig gegessen"); - left.signal(); - right.signal(); + left.canEat.signal(); + right.canEat.signal(); } finally { table.unlock(); } } private void eat() throws InterruptedException { - Thread.sleep((long) (Math.random() * MAX_EATING_DURATION_MS)); + Thread.sleep(random.nextInt(MAX_EATING_DURATION_MS)); } @@ -101,22 +109,14 @@ public class Philosopher extends Thread implements IPhilosopher { private void think() throws InterruptedException { log(seat, "denkt"); - Thread.sleep((long) (Math.random() * MAX_THINKING_DURATION_MS)); + Thread.sleep(random.nextInt(MAX_THINKING_DURATION_MS)); table.lock(); try { - left.signal(); - right.signal(); + left.canEat.signal(); + right.canEat.signal(); } finally { table.unlock(); } } - public void signal() { - table.lock(); - try { - canEat.signal(); - } finally { - table.unlock(); - } - } }