Advertisement
Josif_tepe

Untitled

Apr 4th, 2021
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.91 KB | None | 0 0
  1. import java.util.concurrent.Semaphore;
  2.  
  3. public class DiningPhilosophers {
  4.     static Fork[] forks = new Fork[6];
  5.     static Philosopher[] philosophers = new Philosopher[6];
  6.  
  7.     public static void main(String[] args) {
  8.         for(int i = 0; i < 6; i++) {
  9.             forks[i] = new Fork();
  10.         }
  11.         for(int i = 0; i < 6; i++) {
  12.             philosophers[i] = new Philosopher("P" + i, forks[i], forks[(i + 1) % 6]);
  13.  
  14.         }
  15.         for(int i = 0; i < 6; i++) {
  16.             philosophers[i].start();
  17.         }
  18.         for(int i = 0; i < 6; i++) {
  19.             try {
  20.                 philosophers[i].join();
  21.             }
  22.             catch(InterruptedException e) {
  23.  
  24.             }
  25.         }
  26.     }
  27.     static class Fork {
  28.         Semaphore fork_semaphore = new Semaphore(1);
  29.         void take_fork() {
  30.             try {
  31.                 fork_semaphore.acquire();
  32.             }
  33.             catch (InterruptedException e) {
  34.  
  35.             }
  36.         }
  37.         void put_back_fork() {
  38.             fork_semaphore.release();
  39.         }
  40.     }
  41.     static class Philosopher extends Thread {
  42.         String name;
  43.         Fork left_fork;
  44.         Fork right_fork;
  45.         Philosopher(String _name, Fork _left, Fork _right) {
  46.             name = _name;
  47.             left_fork = _left;
  48.             right_fork = _right;
  49.         }
  50.         @Override
  51.         public void run() {
  52.             left_fork.take_fork();
  53.             right_fork.take_fork();
  54.             eat();
  55.             left_fork.put_back_fork();
  56.             right_fork.put_back_fork();
  57.             think();
  58.         }
  59.         void eat() {
  60.             System.out.println(name + " is eating!");
  61.             try {
  62.                 Thread.sleep(100);
  63.             }
  64.             catch (InterruptedException e) {
  65.  
  66.             }
  67.         }
  68.         void think() {
  69.             System.out.println(name + " is thinking!");
  70.         }
  71.     }
  72. }
  73.  
  74. /// 1 2 3 4 5 6
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement