Assigment finished (wahrscheinlich lol)

main
2wenty1ne 2024-10-28 14:56:22 +01:00
parent 5ad8774c53
commit fad4d1925e
1 changed files with 41 additions and 6 deletions

View File

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