Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashSet;
- import java.util.Random;
- import java.util.concurrent.Semaphore;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- class Demo {
- public static final int NUM_PHILOSOPHERS = 100;
- public static void main(String[] args) throws InterruptedException {
- long startTime = System.nanoTime();
- DiningPhilosophers.runTest();
- long endTime = System.nanoTime();
- System.out.printf("It took %f seconds for %d philosophers to eat and think %d times each.",
- (endTime - startTime) * 0.000000001, NUM_PHILOSOPHERS, NUM_PHILOSOPHERS);
- }
- }
- public class DiningPhilosophers {
- static final int NUM_PHILOSOPHERS = Demo.NUM_PHILOSOPHERS;
- private static final Random random = new Random(System.currentTimeMillis());
- private final Semaphore[] forks = new Semaphore[NUM_PHILOSOPHERS];
- static Lock lock;
- public DiningPhilosophers() {
- for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
- forks[i] = new Semaphore(1);
- }
- lock = new ReentrantLock();
- }
- public void lifecycleOfPhilosopher(int id) throws InterruptedException {
- for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
- think();
- eat(id);
- }
- }
- void think() throws InterruptedException {
- Thread.sleep(random.nextInt(50));
- }
- void eat(int id) {
- // TODO: synchronize
- // Each philosopher will try and grab the forks on his left and right side
- // E.g we have 100 philosophers and 100 forks between them
- // Philosopher with id 99(the last one) will try and grab the 99th and the 1st(fork[0]) fork
- lock.lock();
- if (forks[id % NUM_PHILOSOPHERS].tryAcquire() &&
- forks[(id + 1) % NUM_PHILOSOPHERS].tryAcquire()) {
- System.out.printf("Philosopher %d eating. . .\n", id);
- forks[id % NUM_PHILOSOPHERS].release();
- forks[(id + 1) % NUM_PHILOSOPHERS].release();
- }
- lock.unlock();
- }
- static void runPhilosopher(DiningPhilosophers dp, int id) {
- try {
- dp.lifecycleOfPhilosopher(id);
- } catch (InterruptedException ie) {
- ie.printStackTrace();
- }
- }
- public static void runTest() throws InterruptedException {
- final DiningPhilosophers dp = new DiningPhilosophers();
- HashSet<Thread> threads = new HashSet<>();
- for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
- int finalI = i;
- threads.add(new Thread(() -> runPhilosopher(dp, finalI)));
- }
- for (Thread t : threads)
- t.start();
- for (Thread t : threads)
- t.join();
- }
- }
Add Comment
Please, Sign In to add comment