51 lines
1.5 KiB
Java
51 lines
1.5 KiB
Java
// threads/Philosopher.java
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
// Visit http://OnJava8.com for more book information.
|
|
// A dining philosopher
|
|
import java.util.concurrent.*;
|
|
import java.util.*;
|
|
|
|
public class Philosopher implements Runnable {
|
|
private Chopstick left;
|
|
private Chopstick right;
|
|
private final int id;
|
|
private final int ponderFactor;
|
|
private SplittableRandom rand = new SplittableRandom(47);
|
|
private void pause() throws InterruptedException {
|
|
if(ponderFactor == 0) return;
|
|
TimeUnit.MILLISECONDS.sleep(
|
|
rand.nextInt(ponderFactor * 250));
|
|
}
|
|
public Philosopher(Chopstick left, Chopstick right,
|
|
int ident, int ponder) {
|
|
this.left = left;
|
|
this.right = right;
|
|
id = ident;
|
|
ponderFactor = ponder;
|
|
}
|
|
@Override
|
|
public void run() {
|
|
try {
|
|
while(!Thread.interrupted()) {
|
|
System.out.println(this + " " + "thinking");
|
|
pause();
|
|
// Philosopher becomes hungry
|
|
System.out.println(this + " " + "grabbing right");
|
|
right.take();
|
|
System.out.println(this + " " + "grabbing left");
|
|
left.take();
|
|
System.out.println(this + " " + "eating");
|
|
pause();
|
|
right.drop();
|
|
left.drop();
|
|
}
|
|
} catch(InterruptedException e) {
|
|
System.out.println(
|
|
this + " " + "exiting via interrupt");
|
|
}
|
|
}
|
|
@Override
|
|
public String toString() { return "Philosopher " + id; }
|
|
}
|