From fad4d1925e99292bf6934b676187d532da48d463 Mon Sep 17 00:00:00 2001 From: 2wenty1ne Date: Mon, 28 Oct 2024 14:56:22 +0100 Subject: [PATCH] Assigment finished (wahrscheinlich lol) --- .../src/main/java/pp/Philosopher.java | 47 ++++++++++++++++--- 1 file changed, 41 insertions(+), 6 deletions(-) diff --git a/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java b/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java index 3a06a6c..d25af7a 100644 --- a/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java +++ b/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java @@ -1,47 +1,72 @@ package pp; import java.util.Random; +import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; +import static pp.PhilosopherExperiment.MAX_EATING_DURATION_MS; import static pp.PhilosopherExperiment.MAX_THINKING_DURATION_MS; public class Philosopher extends Thread implements IPhilosopher { private final Random random; + private volatile boolean stop; + private int seat; private Philosopher left; private Philosopher right; private Lock table; - private volatile boolean stop; + public boolean eating; + public Condition condition; + public Philosopher() { - this.stop = false; this.random = new Random(); + this.stop = false; + this.eating = false; } @Override public void run() { + log("starting"); try { while (!this.stop) { - // TODO think(); eat(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } + log("stopped;"); } private void think() throws InterruptedException { - // TODO Thread.sleep(this.random.nextInt(MAX_THINKING_DURATION_MS)); } - private void eat() { - // TODO + private void eat() throws InterruptedException { + this.table.lock(); + try { + while (this.left.eating || this.right.eating) { + this.condition.await(); + } + log("left nor right eating"); + this.eating = true; + log("eating"); + Thread.sleep(this.random.nextInt(MAX_EATING_DURATION_MS)); + + this.eating = false; + this.left.condition.signal(); + this.right.condition.signal(); + + log("done eating"); + } finally { + table.unlock(); + } } @Override public void stopPhilosopher() { + log("stopping"); this.stop = true; interrupt(); } @@ -64,5 +89,15 @@ public class Philosopher extends Thread implements IPhilosopher { @Override public void setTable(Lock table) { this.table = table; + this.condition = this.table.newCondition(); + } + + private void log(String message) { + synchronized (Philosopher.class) { + for (var i = 1; i <= this.seat; i++) { + System.out.print(" "); + } + System.out.println(threadId() + " " + message); + } } }