parent
82f41974d1
commit
28611e3e2f
|
@ -3,6 +3,7 @@ package pp;
|
|||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import static pp.PhilosopherExperiment.*;
|
||||
import java.util.Random;
|
||||
|
||||
|
||||
public class Philosopher extends Thread implements IPhilosopher {
|
||||
|
@ -13,6 +14,13 @@ public class Philosopher extends Thread implements IPhilosopher {
|
|||
private Condition canEat;
|
||||
private volatile boolean eating = false;
|
||||
private volatile boolean stopped = false;
|
||||
private final Random random;
|
||||
|
||||
public Philosopher() {
|
||||
this.random = new Random();
|
||||
this.seat = 0;
|
||||
this.stopped = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLeft(IPhilosopher left) {
|
||||
|
@ -71,15 +79,15 @@ public class Philosopher extends Thread implements IPhilosopher {
|
|||
try {
|
||||
eating = false;
|
||||
log(seat, "hat fertig gegessen");
|
||||
left.signal();
|
||||
right.signal();
|
||||
left.canEat.signal();
|
||||
right.canEat.signal();
|
||||
} finally {
|
||||
table.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private void eat() throws InterruptedException {
|
||||
Thread.sleep((long) (Math.random() * MAX_EATING_DURATION_MS));
|
||||
Thread.sleep(random.nextInt(MAX_EATING_DURATION_MS));
|
||||
}
|
||||
|
||||
|
||||
|
@ -101,22 +109,14 @@ public class Philosopher extends Thread implements IPhilosopher {
|
|||
|
||||
private void think() throws InterruptedException {
|
||||
log(seat, "denkt");
|
||||
Thread.sleep((long) (Math.random() * MAX_THINKING_DURATION_MS));
|
||||
Thread.sleep(random.nextInt(MAX_THINKING_DURATION_MS));
|
||||
table.lock();
|
||||
try {
|
||||
left.signal();
|
||||
right.signal();
|
||||
left.canEat.signal();
|
||||
right.canEat.signal();
|
||||
} finally {
|
||||
table.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void signal() {
|
||||
table.lock();
|
||||
try {
|
||||
canEat.signal();
|
||||
} finally {
|
||||
table.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue