Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java.util.concurrent.Semaphore;
- class Demonstration {
- public static void main(String[] args) throws Exception {
- DiningPhilosophers diningPhilosophers = new DiningPhilosophers();
- Thread[] threads = new Thread[5];
- for (int i = 0; i < 5; i++) {
- final int index = i;
- threads[i] =
- new Thread(
- () -> {
- try {
- diningPhilosophers.lifeCycleOfPhilosopher(index);
- } catch (InterruptedException e) {
- System.out.println("Philosopher is interrupted");
- }
- });
- }
- for (Thread thread : threads) {
- thread.start();
- }
- for (Thread thread : threads) {
- thread.join();
- }
- }
- }
- class DiningPhilosophers {
- private Semaphore[] forks = new Semaphore[5];
- private static Random random = new Random(System.currentTimeMillis());
- public DiningPhilosophers() {
- for (int i = 0; i < 5; i++) {
- forks[i] = new Semaphore(1);
- }
- }
- public void lifeCycleOfPhilosopher(int id) throws InterruptedException {
- while (true) {
- contemplate(id);
- eat(id);
- }
- }
- private void contemplate(int id) throws InterruptedException {
- System.out.println("Philosopher " + id + " is contemplating.");
- Thread.sleep(random.nextInt(100));
- }
- private void eat(int id) throws InterruptedException {
- if (id == 0) {
- forks[(id + 1) % 5].acquire();
- forks[id].acquire();
- } else {
- forks[id].acquire();
- forks[(id + 1) % 5].acquire();
- }
- eatNoodle(id);
- forks[id].release();
- forks[(id + 1) % 5].release();
- }
- private void eatNoodle(int id) throws InterruptedException {
- System.out.println("Philosopher " + id + " is eating noodle");
- Thread.sleep(random.nextInt(100));
- System.out.println("Philosopher " + id + " finished eating noodle");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement