2016-11-23 09:05:26 -08:00
|
|
|
// concurrent/Philosopher.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.*;
|
2016-12-25 12:36:49 -08:00
|
|
|
import java.util.stream.*;
|
|
|
|
import java.util.concurrent.*;
|
|
|
|
import static java.util.concurrent.TimeUnit.*;
|
|
|
|
import java.util.concurrent.atomic.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
2016-12-25 12:36:49 -08:00
|
|
|
class Philosopher implements Runnable {
|
|
|
|
static class Chopstick {}
|
|
|
|
public static final int QUANTITY = 5;
|
|
|
|
static Queue<String> trace =
|
|
|
|
new ConcurrentLinkedQueue<>();
|
|
|
|
static AtomicBoolean running =
|
|
|
|
new AtomicBoolean(true);
|
|
|
|
public static
|
|
|
|
List<BlockingQueue<Chopstick>> chopsticks =
|
|
|
|
IntStream.range(0, Philosopher.QUANTITY)
|
|
|
|
.mapToObj(i -> {
|
|
|
|
BlockingQueue<Chopstick> bd =
|
|
|
|
new ArrayBlockingQueue<>(1);
|
|
|
|
bd.add(new Chopstick());
|
|
|
|
return bd;
|
|
|
|
})
|
|
|
|
.collect(Collectors.toList());
|
|
|
|
private final int seatNumber;
|
|
|
|
private final int left, right;
|
|
|
|
public Philosopher(int seatNumber) {
|
|
|
|
this.seatNumber = left = seatNumber;
|
|
|
|
right = (seatNumber + 1) % QUANTITY;
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public void run() {
|
|
|
|
try {
|
2016-12-25 12:36:49 -08:00
|
|
|
while(running.get()) {
|
|
|
|
trace.add(this + " thinking");
|
2015-06-15 17:47:35 -07:00
|
|
|
// Philosopher becomes hungry
|
2016-12-25 12:36:49 -08:00
|
|
|
trace.add(this + " grabbing right");
|
|
|
|
Chopstick rightStick =
|
|
|
|
chopsticks.get(right).poll(2, SECONDS);
|
|
|
|
trace.add(this + " grabbing left");
|
|
|
|
Chopstick leftStick =
|
|
|
|
chopsticks.get(left).poll(2, SECONDS);
|
|
|
|
trace.add(this + " eating");
|
|
|
|
// Finished, return chopsticks to table:
|
|
|
|
chopsticks.get(right).put(rightStick);
|
|
|
|
chopsticks.get(left).put(leftStick);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
} catch(InterruptedException e) {
|
2016-12-25 12:36:49 -08:00
|
|
|
trace.add("exiting via interrupt");
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
@Override
|
2016-12-25 12:36:49 -08:00
|
|
|
public String toString() {
|
|
|
|
return "P" + seatNumber;
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|