PP_SL/pp.A1-CondPhilosophers/src/main/java/pp/Philosopher.java

101 lines
2.0 KiB
Java

package pp;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Philosopher extends Thread implements IPhilosopher {
private int seat;
private Philosopher rechts;
private Philosopher links;
private Lock table;
private Condition canEat;
private volatile boolean stopped;
private volatile boolean eating;
private final Random random;
public Philosopher() {
this.random = new Random();
this.seat = 0;
this.stopped = false;
}
@Override
public void run() {
try {
while (this.stopped == false) {
think();
eat();
}
} catch (InterruptedException e) {
}
}
private void eat() throws InterruptedException {
table.lock();
try {
while (this.links.eating || this.rechts.eating) {
log(seat, " : isst gerade!");
this.canEat.await();
}
this.eating = true;
} finally {
table.unlock();
}
Thread.sleep(this.random.nextInt(PhilosopherExperiment.MAX_EATING_DURATION_MS));
}
private void think() {
table.lock();
this.links.canEat.signal();
this.rechts.canEat.signal();
table.unlock();
try {
Thread.sleep(random.nextInt(PhilosopherExperiment.MAX_THINKING_DURATION_MS));
log(seat, " : denkt gerade !");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void setLeft(IPhilosopher left) {
// TODO Auto-generated method stub
// Cast auf Philosopher erforderlich
this.links = (Philosopher) left;
}
@Override
public void setRight(IPhilosopher right) {
// TODO Auto-generated method stub
// Cast auf Philosopher erforderlich
this.rechts = (Philosopher) right;
}
@Override
public void setSeat(int seat) {
this.seat = seat;
}
@Override
public void setTable(Lock table) {
// TODO Auto-generated method stub
this.table = table;
canEat = this.table.newCondition();
}
@Override
public void stopPhilosopher() {
this.stopped = true;
interrupt();
}
}