signal
constructor
Test-SJ
Shahnam Javidnia 2025-05-04 21:48:06 +02:00
parent 82f41974d1
commit 28611e3e2f
1 changed files with 14 additions and 14 deletions

View File

@ -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();
}
}
}