OnJava8-Examples/threads/FixedDiningPhilosophers.java

61 lines
1.8 KiB
Java
Raw Normal View History

2016-07-05 14:46:09 -06:00
// threads/FixedDiningPhilosophers.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.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Dining philosophers without deadlock
2015-06-15 17:47:35 -07:00
// {Args: 5 5 timeout}
import java.util.concurrent.*;
public class FixedDiningPhilosophers {
2016-01-25 18:05:55 -08:00
public static void
main(String[] args) throws Exception {
2015-06-15 17:47:35 -07:00
int ponder = 5;
if(args.length > 0)
ponder = Integer.parseInt(args[0]);
int size = 5;
if(args.length > 1)
size = Integer.parseInt(args[1]);
2016-01-25 18:05:55 -08:00
ExecutorService es = Executors.newCachedThreadPool();
2015-06-15 17:47:35 -07:00
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))
2016-01-25 18:05:55 -08:00
es.execute(new Philosopher(
2015-06-15 17:47:35 -07:00
sticks[i], sticks[i+1], i, ponder));
else
2016-01-25 18:05:55 -08:00
es.execute(new Philosopher(
2015-06-15 17:47:35 -07:00
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();
}
2016-01-25 18:05:55 -08:00
es.shutdownNow();
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output: (First and last 10 Lines)
2015-06-15 17:47:35 -07:00
Philosopher 4 thinking
Philosopher 3 thinking
Philosopher 0 thinking
Philosopher 2 thinking
Philosopher 1 thinking
Philosopher 4 grabbing right
Philosopher 1 grabbing right
Philosopher 2 grabbing right
Philosopher 2 grabbing left
Philosopher 0 grabbing right
________...________...________...________...________
Philosopher 2 grabbing right
Philosopher 1 exiting via interrupt
Philosopher 0 exiting via interrupt
Philosopher 3 exiting via interrupt
Philosopher 4 grabbing right
Philosopher 2 grabbing left
Philosopher 4 grabbing left
Philosopher 2 exiting via interrupt
Philosopher 4 eating
Philosopher 4 exiting via interrupt
2015-09-07 11:44:36 -06:00
*/