57 lines
1.5 KiB
Java
57 lines
1.5 KiB
Java
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();
|
|
}
|
|
}
|
|
|