2016-12-25 12:36:49 -08:00
|
|
|
// concurrent/DiningPhilosophers.java
|
2016-12-30 17:23:13 -08:00
|
|
|
// (c)2017 MindView LLC: see Copyright.txt
|
2016-12-25 12:36:49 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-12-29 17:05:59 -08:00
|
|
|
// Hidden deadlock
|
2017-05-17 21:38:05 -06:00
|
|
|
// {ExcludeFromGradle} Gradle has trouble
|
2016-12-29 17:05:59 -08:00
|
|
|
import java.util.*;
|
2016-12-25 12:36:49 -08:00
|
|
|
import java.util.concurrent.*;
|
2017-01-18 16:10:15 -08:00
|
|
|
import onjava.Nap;
|
2016-12-25 12:36:49 -08:00
|
|
|
|
|
|
|
public class DiningPhilosophers {
|
2016-12-29 17:05:59 -08:00
|
|
|
private StickHolder[] sticks;
|
|
|
|
private Philosopher[] philosophers;
|
|
|
|
public DiningPhilosophers(int n) {
|
|
|
|
sticks = new StickHolder[n];
|
|
|
|
Arrays.setAll(sticks, i -> new StickHolder());
|
|
|
|
philosophers = new Philosopher[n];
|
|
|
|
Arrays.setAll(philosophers, i ->
|
|
|
|
new Philosopher(i,
|
|
|
|
sticks[i], sticks[(i + 1) % n])); // [1]
|
2017-01-18 16:10:15 -08:00
|
|
|
// Fix by reversing stick order for this one:
|
2016-12-29 17:05:59 -08:00
|
|
|
// philosophers[1] = // [2]
|
|
|
|
// new Philosopher(0, sticks[0], sticks[1]);
|
|
|
|
Arrays.stream(philosophers)
|
|
|
|
.forEach(CompletableFuture::runAsync); // [3]
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
// Returns right away:
|
|
|
|
new DiningPhilosophers(5); // [4]
|
|
|
|
// Keeps main() from exiting:
|
2017-01-22 16:48:11 -08:00
|
|
|
new Nap(3, "Shutdown");
|
2016-12-25 12:36:49 -08:00
|
|
|
}
|
|
|
|
}
|