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.Lock;
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Condition;
import static pp.PhilosopherExperiment.*; import static pp.PhilosopherExperiment.*;
import java.util.Random;
public class Philosopher extends Thread implements IPhilosopher { public class Philosopher extends Thread implements IPhilosopher {
@ -13,6 +14,13 @@ public class Philosopher extends Thread implements IPhilosopher {
private Condition canEat; private Condition canEat;
private volatile boolean eating = false; private volatile boolean eating = false;
private volatile boolean stopped = false; private volatile boolean stopped = false;
private final Random random;
public Philosopher() {
this.random = new Random();
this.seat = 0;
this.stopped = false;
}
@Override @Override
public void setLeft(IPhilosopher left) { public void setLeft(IPhilosopher left) {
@ -71,15 +79,15 @@ public class Philosopher extends Thread implements IPhilosopher {
try { try {
eating = false; eating = false;
log(seat, "hat fertig gegessen"); log(seat, "hat fertig gegessen");
left.signal(); left.canEat.signal();
right.signal(); right.canEat.signal();
} finally { } finally {
table.unlock(); table.unlock();
} }
} }
private void eat() throws InterruptedException { 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 { private void think() throws InterruptedException {
log(seat, "denkt"); log(seat, "denkt");
Thread.sleep((long) (Math.random() * MAX_THINKING_DURATION_MS)); Thread.sleep(random.nextInt(MAX_THINKING_DURATION_MS));
table.lock(); table.lock();
try { try {
left.signal(); left.canEat.signal();
right.signal(); right.canEat.signal();
} finally { } finally {
table.unlock(); table.unlock();
} }
} }
public void signal() {
table.lock();
try {
canEat.signal();
} finally {
table.unlock();
}
}
} }