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

56 lines
1.8 KiB
Java
Raw Normal View History

2024-10-24 21:49:25 +02:00
package philosopher2;
import src.Chopstick;
public class Philosopher implements Runnable {
private final Chopstick leftChopstick;
private final Chopstick rightChopstick;
private final boolean isRightHanded; // Asymmetry flag
public Philosopher(Chopstick leftChopstick, Chopstick rightChopstick, boolean isRightHanded) {
this.leftChopstick = leftChopstick;
this.rightChopstick = rightChopstick;
this.isRightHanded = isRightHanded;
}
@Override
public void run() {
try {
while (true) {
think();
if (isRightHanded) {
synchronized (rightChopstick) {
rightChopstick.pickUp();
synchronized (leftChopstick) {
leftChopstick.pickUp();
eat();
leftChopstick.putDown();
}
rightChopstick.putDown();
}
} else {
synchronized (leftChopstick) {
leftChopstick.pickUp();
synchronized (rightChopstick) {
rightChopstick.pickUp();
eat();
rightChopstick.putDown();
}
leftChopstick.putDown();
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void think() {
System.out.println(Thread.currentThread().getName() + " is thinking.");
}
private void eat() {
System.out.println(Thread.currentThread().getName() + " is eating.");
}
}