Update
parent
4babf0c797
commit
3cee7198b9
|
@ -1,20 +1,76 @@
|
|||
package pp;
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
|
||||
public class Philosopher extends Thread implements IPhilosopher {
|
||||
private int seat;
|
||||
private Philosopher rechts;
|
||||
private Philosopher links;
|
||||
private Lock table;
|
||||
private Condition condition ;
|
||||
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) {
|
||||
// Thread was interrupted, exit gracefully
|
||||
}
|
||||
}
|
||||
|
||||
private void eat() throws InterruptedException {
|
||||
table.lock();
|
||||
try {
|
||||
|
||||
while(this.links.eating || this.rechts.eating)
|
||||
this.condition.await();
|
||||
this.eating = true;
|
||||
}finally {
|
||||
table.unlock();
|
||||
}
|
||||
Thread.sleep(this.random.nextInt(PhilosopherExperiment.MAX_EATING_DURATION_MS));
|
||||
}
|
||||
|
||||
private void think() {
|
||||
table.lock();
|
||||
this.links.condition.signal();
|
||||
this.rechts.condition.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
|
||||
|
@ -25,12 +81,15 @@ public class Philosopher extends Thread implements IPhilosopher {
|
|||
@Override
|
||||
public void setTable(Lock table) {
|
||||
// TODO Auto-generated method stub
|
||||
this.table = table;
|
||||
condition = this.table.newCondition();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopPhilosopher() {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
|
||||
this.stopped = true;
|
||||
interrupt();
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue