Advertisement
Jaydeep999997

Dining Philosopher - Only 4

Oct 22nd, 2024
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.97 KB | Source Code | 0 0
  1. import java.util.Random;
  2. import java.util.concurrent.Semaphore;
  3.  
  4. class Demonstration {
  5.   public static void main(String[] args) throws Exception {
  6.     DiningPhilosophers diningPhilosophers = new DiningPhilosophers();
  7.     Thread[] threads = new Thread[5];
  8.     for (int i = 0; i < 5; i++) {
  9.       final int index = i;
  10.       threads[i] =
  11.           new Thread(
  12.               () -> {
  13.                 try {
  14.                   diningPhilosophers.lifeCycleOfPhilosopher(index);
  15.                 } catch (InterruptedException e) {
  16.                   System.out.println("Philosopher is interrupted");
  17.                 }
  18.               });
  19.     }
  20.     for (Thread thread : threads) {
  21.       thread.start();
  22.     }
  23.     for (Thread thread : threads) {
  24.       thread.join();
  25.     }
  26.   }
  27. }
  28.  
  29. class DiningPhilosophers {
  30.   private Semaphore[] forks = new Semaphore[5];
  31.   private Semaphore currentlyEatingPhilosophers = new Semaphore(4);
  32.   private static Random random = new Random(System.currentTimeMillis());
  33.  
  34.   public DiningPhilosophers() {
  35.     for (int i = 0; i < 5; i++) {
  36.       forks[i] = new Semaphore(1);
  37.     }
  38.   }
  39.  
  40.   public void lifeCycleOfPhilosopher(int id) throws InterruptedException {
  41.     while (true) {
  42.       contemplate(id);
  43.       eat(id);
  44.     }
  45.   }
  46.  
  47.   private void contemplate(int id) throws InterruptedException {
  48.     System.out.println("Philosopher " + id + " is contemplating.");
  49.     Thread.sleep(random.nextInt(100));
  50.   }
  51.  
  52.   private void eat(int id) throws InterruptedException {
  53.     currentlyEatingPhilosophers.acquire();
  54.     forks[id].acquire();
  55.     forks[(id + 1) % 5].acquire();
  56.     eatNoodle(id);
  57.     forks[id].release();
  58.     forks[(id + 1) % 5].release();
  59.     currentlyEatingPhilosophers.release();
  60.   }
  61.  
  62.   private void eatNoodle(int id) throws InterruptedException {
  63.     System.out.println("Philosopher " + id + " is eating noodle");
  64.     Thread.sleep(random.nextInt(100));
  65.     System.out.println("Philosopher " + id + " finished eating noodle");
  66.   }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement