Advertisement
Jaydeep999997

Dining Philosopher - Limiting Ps

Oct 22nd, 2024
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 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 static Random random = new Random(System.currentTimeMillis());
  32.  
  33.   public DiningPhilosophers() {
  34.     for (int i = 0; i < 5; i++) {
  35.       forks[i] = new Semaphore(1);
  36.     }
  37.   }
  38.  
  39.   public void lifeCycleOfPhilosopher(int id) throws InterruptedException {
  40.     while (true) {
  41.       contemplate(id);
  42.       eat(id);
  43.     }
  44.   }
  45.  
  46.   private void contemplate(int id) throws InterruptedException {
  47.     System.out.println("Philosopher " + id + " is contemplating.");
  48.     Thread.sleep(random.nextInt(100));
  49.   }
  50.  
  51.   private void eat(int id) throws InterruptedException {
  52.     if (id == 0) {
  53.       forks[(id + 1) % 5].acquire();
  54.       forks[id].acquire();
  55.     } else {
  56.       forks[id].acquire();
  57.       forks[(id + 1) % 5].acquire();
  58.     }
  59.  
  60.     eatNoodle(id);
  61.  
  62.     forks[id].release();
  63.     forks[(id + 1) % 5].release();
  64.   }
  65.  
  66.   private void eatNoodle(int id) throws InterruptedException {
  67.     System.out.println("Philosopher " + id + " is eating noodle");
  68.     Thread.sleep(random.nextInt(100));
  69.     System.out.println("Philosopher " + id + " finished eating noodle");
  70.   }
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement