97 lines
2.6 KiB
Java
97 lines
2.6 KiB
Java
package pp;
|
|
|
|
import java.util.concurrent.locks.Condition;
|
|
import java.util.concurrent.locks.Lock;
|
|
|
|
public class Philosopher extends Thread implements IPhilosopher {
|
|
static final int MAX_THINKING_DURATION_MS = 1000; //aus Vorlesungsbeispiel
|
|
static final int MAX_EATING_DURATION_MS = 3000; //aus Vorlesungsbeispiel
|
|
boolean stop = false;
|
|
private int seat;
|
|
private Lock table;
|
|
private Condition cond;
|
|
private Philosopher left;
|
|
private Philosopher right;
|
|
private boolean essen;
|
|
private int gegessen = 0;
|
|
|
|
@Override
|
|
public void setLeft(IPhilosopher left) {
|
|
// TODO Auto-generated method stub
|
|
// Cast auf Philosopher erforderlich
|
|
this.left = (Philosopher) left;
|
|
}
|
|
|
|
@Override
|
|
public void setRight(IPhilosopher right) {
|
|
// TODO Auto-generated method stub
|
|
// Cast auf Philosopher erforderlich
|
|
this.right = (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;
|
|
this.cond = table.newCondition();
|
|
}
|
|
|
|
@Override
|
|
public void stopPhilosopher() {
|
|
// TODO Auto-generated method stub
|
|
log(seat, "stopping");
|
|
this.stop = true;
|
|
interrupt();
|
|
}
|
|
|
|
@Override
|
|
public void run() {
|
|
try {
|
|
while (!stop) {
|
|
log(seat, "überlegen");
|
|
Thread.sleep(MAX_THINKING_DURATION_MS);
|
|
try {
|
|
startEating();
|
|
log(seat, "essen");
|
|
Thread.sleep(MAX_EATING_DURATION_MS);
|
|
gegessen = gegessen + 1;
|
|
log(seat, "gegessen " + gegessen);
|
|
} finally {
|
|
stopEating();
|
|
}
|
|
}
|
|
} catch (InterruptedException e) {
|
|
//Hier ist eine Exception gefunden worden
|
|
System.out.println("Hier ist ein Thread unterbrochen worden");
|
|
}
|
|
}
|
|
|
|
private void startEating() throws InterruptedException {
|
|
table.lock();
|
|
try {
|
|
while (left.essen || right.essen) {
|
|
cond.await();
|
|
}
|
|
essen = true;
|
|
} finally {
|
|
table.unlock();
|
|
}
|
|
}
|
|
|
|
private void stopEating() throws InterruptedException {
|
|
table.lock();
|
|
try {
|
|
essen = false;
|
|
left.cond.signal();
|
|
right.cond.signal();
|
|
} finally {
|
|
table.unlock();
|
|
}
|
|
}
|
|
}
|