diff --git a/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java b/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java index d470137..df328c9 100644 --- a/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java +++ b/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java @@ -32,6 +32,7 @@ public class Philosopher extends Thread implements IPhilosopher { } } catch (InterruptedException e) { } + log(seat,"beendet"); } private void eat() throws InterruptedException { @@ -39,10 +40,11 @@ public class Philosopher extends Thread implements IPhilosopher { try { while (this.links.eating || this.rechts.eating) { - log(seat, " : isst gerade!"); + log(seat,"warten!"); this.canEat.await(); } this.eating = true; + log(seat, " : isst gerade!"); } finally { table.unlock(); } @@ -52,12 +54,12 @@ public class Philosopher extends Thread implements IPhilosopher { private void think() throws InterruptedException { this.table.lock(); - table.unlock(); try { if (this.eating) this.eating = false; this.links.canEat.signal(); this.rechts.canEat.signal(); + log(seat,"denken"); } finally { this.table.unlock(); @@ -100,6 +102,37 @@ public class Philosopher extends Thread implements IPhilosopher { interrupt(); } - + public static void main(String[] args) throws InterruptedException { + int numPhilosophers = 5; + Lock table = new ReentrantLock(); + Philosopher[] philosophers = new Philosopher[numPhilosophers]; + + for (int i = 0; i < numPhilosophers; i++) { + philosophers[i] = new Philosopher(); + philosophers[i].setSeat(i); + philosophers[i].setTable(table); + } + + for (int i = 0; i < numPhilosophers; i++) { + philosophers[i].setLeft(philosophers[(i + numPhilosophers - 1) % numPhilosophers]); + philosophers[i].setRight(philosophers[(i + 1) % numPhilosophers]); + } + + for (Philosopher p : philosophers) { + p.start(); + } + + Thread.sleep(10_000); // Laufzeit: 10 Sekunden + + for (Philosopher p : philosophers) { + p.stopPhilosopher(); + } + + for (Philosopher p : philosophers) { + p.join(); + } + + System.out.println("Experiment beendet!"); + } }