PP-Labs_WS-2024-2025/eigenes/philosopher3/Philosopher.java

57 lines
1.5 KiB
Java
Raw Normal View History

2024-10-24 21:49:25 +02:00
package philosopher3;
import src.Chopstick;
public class Philosopher implements Runnable {
private final Chopstick leftChopstick;
private final Chopstick rightChopstick;
public Philosopher(Chopstick leftChopstick, Chopstick rightChopstick) {
this.leftChopstick = leftChopstick;
this.rightChopstick = rightChopstick;
}
@Override
public void run() {
try {
while (true) {
think();
if (tryToEat()) {
eat();
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void think() {
System.out.println(Thread.currentThread().getName() + " is thinking.");
}
private boolean tryToEat() throws InterruptedException {
synchronized (leftChopstick) {
leftChopstick.pickUp();
if (!tryPickUpRightChopstick()) {
leftChopstick.putDown();
return false; // Couldn't get both chopsticks, return to thinking
}
}
return true;
}
private boolean tryPickUpRightChopstick() throws InterruptedException {
synchronized (rightChopstick) {
rightChopstick.pickUp();
return true;
}
}
private void eat() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " is eating.");
rightChopstick.putDown();
leftChopstick.putDown();
}
}