forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFixedDiningPhilosophers.java
More file actions
60 lines (59 loc) · 1.82 KB
/
FixedDiningPhilosophers.java
File metadata and controls
60 lines (59 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// threads/FixedDiningPhilosophers.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Dining philosophers without deadlock
// {java FixedDiningPhilosophers 5 5 timeout}
import java.util.concurrent.*;
public class FixedDiningPhilosophers {
public static void
main(String[] args) throws Exception {
int ponder = 5;
if(args.length > 0)
ponder = Integer.parseInt(args[0]);
int size = 5;
if(args.length > 1)
size = Integer.parseInt(args[1]);
ExecutorService es = Executors.newCachedThreadPool();
Chopstick[] sticks = new Chopstick[size];
for(int i = 0; i < size; i++)
sticks[i] = new Chopstick();
for(int i = 0; i < size; i++)
if(i < (size-1))
es.execute(new Philosopher(
sticks[i], sticks[i+1], i, ponder));
else
es.execute(new Philosopher(
sticks[0], sticks[i], i, ponder));
if(args.length == 3 && args[2].equals("timeout"))
TimeUnit.SECONDS.sleep(5);
else {
System.out.println("Press 'Enter' to quit");
System.in.read();
}
es.shutdownNow();
}
}
/* Output: (First and Last 10 Lines)
Philosopher 1 thinking
Philosopher 4 thinking
Philosopher 2 thinking
Philosopher 0 thinking
Philosopher 3 thinking
Philosopher 1 grabbing right
Philosopher 2 grabbing right
Philosopher 4 grabbing right
Philosopher 4 grabbing left
Philosopher 4 eating
...________...________...________...________...
Philosopher 1 thinking
Philosopher 0 grabbing left
Philosopher 0 eating
Philosopher 2 eating
Philosopher 1 grabbing right
Philosopher 3 exiting via interrupt
Philosopher 1 exiting via interrupt
Philosopher 2 exiting via interrupt
Philosopher 0 exiting via interrupt
Philosopher 4 exiting via interrupt
*/