pull/2/head
obaya 2025-05-05 10:37:03 +02:00
parent 043fcbc994
commit 591c8fec1b
1 changed files with 36 additions and 3 deletions

View File

@ -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!");
}
}