|
| 1 | +package org.ashfaq.dev.problems.DiningPhilosophers; |
| 2 | + |
| 3 | +import java.util.Random; |
| 4 | + |
| 5 | +public class Philosopher implements Runnable { |
| 6 | + |
| 7 | + private int id; |
| 8 | + private Chopsticks leftChopStick; |
| 9 | + private Chopsticks rightChopStick; |
| 10 | + private volatile boolean isFull = false; |
| 11 | + private Random random; |
| 12 | + private int eatingCounter; |
| 13 | + |
| 14 | + public Philosopher(int id, Chopsticks leftChopStick, Chopsticks rightChopStick){ |
| 15 | + this.id = id; |
| 16 | + this.leftChopStick = leftChopStick; |
| 17 | + this.rightChopStick = rightChopStick; |
| 18 | + this.random = new Random(); |
| 19 | + } |
| 20 | + |
| 21 | + @Override |
| 22 | + public void run() { |
| 23 | + |
| 24 | + try{ |
| 25 | + |
| 26 | + while( !isFull ){ |
| 27 | + |
| 28 | + think(); |
| 29 | + |
| 30 | + if( leftChopStick.pickUp(this, State.LEFT) ){ |
| 31 | + if( rightChopStick.pickUp(this, State.RIGHT)){ |
| 32 | + eat(); |
| 33 | + rightChopStick.putDown(this, State.RIGHT); |
| 34 | + } |
| 35 | + |
| 36 | + leftChopStick.putDown(this, State.LEFT); |
| 37 | + } |
| 38 | + } |
| 39 | + }catch(Exception e){ |
| 40 | + e.printStackTrace(); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + private void think() throws InterruptedException { |
| 45 | + System.out.println(this+" is thinking..."); |
| 46 | + Thread.sleep(this.random.nextInt(1000)); |
| 47 | + } |
| 48 | + |
| 49 | + private void eat() throws InterruptedException { |
| 50 | + System.out.println(this+" is eating..."); |
| 51 | + this.eatingCounter++; |
| 52 | + Thread.sleep(this.random.nextInt(1000)); |
| 53 | + } |
| 54 | + |
| 55 | + public int getEatingCounter(){ |
| 56 | + return this.eatingCounter; |
| 57 | + } |
| 58 | + |
| 59 | + public void setFull(boolean isFull){ |
| 60 | + this.isFull = isFull; |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public String toString() { |
| 65 | + return "Philosopher-"+this.id; |
| 66 | + } |
| 67 | +} |
| 68 | + |
0 commit comments