|
2 | 2 | // (c)2016 MindView LLC: see Copyright.txt |
3 | 3 | // We make no guarantees that this code is fit for any purpose. |
4 | 4 | // Visit http://OnJava8.com for more book information. |
5 | | -import java.util.*; |
6 | | -import java.util.stream.*; |
7 | | -import java.util.concurrent.*; |
8 | | -import static java.util.concurrent.TimeUnit.*; |
9 | | -import java.util.concurrent.atomic.*; |
10 | 5 |
|
11 | | -class Philosopher implements Runnable { |
12 | | - static class Chopstick {} |
13 | | - public static final int QUANTITY = 5; |
14 | | - static Queue<String> trace = |
15 | | - new ConcurrentLinkedQueue<>(); |
16 | | - static AtomicBoolean running = |
17 | | - new AtomicBoolean(true); |
18 | | - public static |
19 | | - List<BlockingQueue<Chopstick>> chopsticks = |
20 | | - IntStream.range(0, Philosopher.QUANTITY) |
21 | | - .mapToObj(i -> { |
22 | | - BlockingQueue<Chopstick> bd = |
23 | | - new ArrayBlockingQueue<>(1); |
24 | | - bd.add(new Chopstick()); |
25 | | - return bd; |
26 | | - }) |
27 | | - .collect(Collectors.toList()); |
28 | | - private final int seatNumber; |
29 | | - private final int left, right; |
30 | | - public Philosopher(int seatNumber) { |
31 | | - this.seatNumber = left = seatNumber; |
32 | | - right = (seatNumber + 1) % QUANTITY; |
| 6 | +public class Philosopher implements Runnable { |
| 7 | + private final int seat; |
| 8 | + private final StickHolder left, right; |
| 9 | + public Philosopher(int seat, |
| 10 | + StickHolder left, StickHolder right) { |
| 11 | + this.seat = seat; |
| 12 | + this.left = left; |
| 13 | + this.right = right; |
33 | 14 | } |
34 | 15 | @Override |
35 | | - public void run() { |
36 | | - try { |
37 | | - while(running.get()) { |
38 | | - trace.add(this + " thinking"); |
39 | | - // Philosopher becomes hungry |
40 | | - trace.add(this + " grabbing right"); |
41 | | - Chopstick rightStick = |
42 | | - chopsticks.get(right).poll(2, SECONDS); |
43 | | - trace.add(this + " grabbing left"); |
44 | | - Chopstick leftStick = |
45 | | - chopsticks.get(left).poll(2, SECONDS); |
46 | | - trace.add(this + " eating"); |
47 | | - // Finished, return chopsticks to table: |
48 | | - chopsticks.get(right).put(rightStick); |
49 | | - chopsticks.get(left).put(leftStick); |
50 | | - } |
51 | | - } catch(InterruptedException e) { |
52 | | - trace.add("exiting via interrupt"); |
53 | | - } |
| 16 | + public String toString() { |
| 17 | + return "P" + seat; |
54 | 18 | } |
55 | 19 | @Override |
56 | | - public String toString() { |
57 | | - return "P" + seatNumber; |
| 20 | + public void run() { |
| 21 | + while(true) { |
| 22 | + // System.out.println("Thinking"); // [1] |
| 23 | + right.pickUp(); |
| 24 | + left.pickUp(); |
| 25 | + System.out.println(this + " eating"); |
| 26 | + right.putDown(); |
| 27 | + left.putDown(); |
| 28 | + } |
58 | 29 | } |
59 | 30 | } |
0 commit comments